home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1997 July: Mac OS SDK / Dev.CD Jul 97 SDK1.toast / Development Kits (Disc 1) / QuickDraw GX / Programming Stuff / Sample Code / Printing Samples / Printer Drivers… / ImageWriter / NewApp.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-06-15  |  75.1 KB  |  2,659 lines  |  [TEXT/MPS ]

  1. /*
  2.     copyright © 1991-1998 Apple Computer Inc.  All rights reserved.
  3.     
  4.     NewApp.c
  5.     This file contains all new API implementations for the ImageWriter driver.
  6.     
  7.     Modification history
  8.     03/19/91        TED                New file today
  9.     04/23/91        Sam Weiss        Changed Inherit to Forward
  10.     05/29/91        TED                Added manual feed and faster mode support
  11.     12/20/93        dmh                Sync'd with the shipping 1.0b3 GX driver.
  12.     03/24/94        Ken Hittleman    Updated manual feed to use gxTrayFeedInfo
  13.     03/30/94        Ken Hittleman    Added call to paper matching CheckStatus when switching to auto-feed
  14.     07/05/94        Ken Hittleman    Removed set color and page size from IW I path, which blew cookies on it
  15.     08/26/94        dmh                Sync'd with the shipping 1.0.1 GX driver.
  16.     06/14/96        cn                Updated to support Universal Interfaces 2.1.
  17. */
  18.  
  19. #include <memory.h>
  20. #include <Errors.h>
  21. #include <ToolUtils.h>
  22. #include <Resources.h>
  23. #include <Packages.h>
  24. #include <GXPrinterDrivers.h>
  25. #include <GXPrinting.h>
  26. #include <FixMath.h>
  27. #include <GXMath.h>
  28. #include <Graphics Routines.h>
  29. #include <GraphicsLibraries.h>
  30. #include <FontLibrary.h>
  31. #include <GXLayout.h>
  32. #include <GXExceptions.h>
  33. #include <PrintingLibraries.h>
  34.  
  35. #include "CommonDefines.h"
  36.  
  37. /* ------------------------------------------------------------------------------------    */
  38. /*    INTERNAL DEFINES                                                                    */
  39. /* ------------------------------------------------------------------------------------    */    
  40.  
  41. // positive error for aborting job and placing on hold
  42. #define kPutJobOnHoldErr            3
  43.  
  44. // timeout (in ticks) for the initial query
  45. #define kQueryTimeout                (7*60);
  46.  
  47. // things this specific driver puts into the DTP config file
  48. #define    kImageWriterConfigType        'ifig'
  49. #define kImageWriterConfigID        (0)            
  50. typedef struct
  51.     {
  52.         Boolean    hasColorRibbon;
  53.         Boolean    hasSheetFeeder;
  54.         Boolean    isImageWriterII;        // is this an ImageWriter II, or an older model?
  55.     } ImageWriterConfigRecord, *ImageWriterConfigPtr, ** ImageWriterConfigHandle;
  56.     
  57. /* Define special characters needed */
  58. #define ESCAPE                (char) 27
  59.  
  60. /* A record to hold a set margins command */
  61. typedef struct SetMarginsRecord
  62.     {
  63.     char        cEscape;                    // ESCAPE character
  64.     char        cCommand;                    // Set Margins command character
  65.     char        cIndentDistance[4];            // number of dots to indent
  66.     } SetMarginsRecord, *SetMarginsPtr;
  67. #define kSetMarginsCommand    (char)'F'        // ImageWriter II uses 'F' for tabbing
  68. #define kSetMarginsSize        6
  69.  
  70. /*     Define a record that can hold one scan line's worth of data, 1280 will
  71.     only happen at 160 dpi. and 14 inch wide paper.   */
  72. typedef struct ScanLineRecord
  73.     {
  74.     char            cColorEscape;                    // ESCAPE character
  75.     char            cSetColorCommand;                // Set color command
  76.     char            cColor;                            // The color
  77.     char            cEscape;                        // ESCAPE character
  78.     char            cCommand;                        // 'enter graphics' command
  79.     char            cLineLength[4];                    // number of dots to print
  80.     char            iTheData[2240];                    // Bits for the data, enough for one line's worth
  81.     } ScanLineRecord, *ScanLinePtr;
  82. #define kGraphicsCommand    (char)'G'        /* graphics printing command */
  83. #define kRepeatGroup        (char)'V'        /* repeat group character */
  84. #define kSetColorCommand     (char)'K'        /* Set color command */
  85. #define kGroupSize            6                /* Size of one group header */
  86.  
  87. #define kScanLineSize         3                /* NOTE: this is just the header size! */
  88.  
  89. #define kStatusCommand        "\033?"            /* request device status/config */
  90.  
  91. // Status flags for PAP status queries
  92. #define    kColorRibbonBit        0
  93. #define kSheetFeederBit        1
  94. #define kPaperOutBit        2
  95. #define kCoverOpenBit        3
  96. #define kOffLineBit            4
  97. #define kPaperJamBit        5
  98. #define kPrinterFaultBit    6
  99. #define kHeadMovingBit        7
  100. #define kPrinterBusyBit        8
  101.  
  102. #define kOutOfPaperMask            (  (0x8000 >> kPaperJamBit) | (0x8000 >> kCoverOpenBit) | (0x8000 >> kOffLineBit) )
  103. #define kPrinterOfflineMask        (  (0x8000 >> kOffLineBit) )
  104. #define kPrinterBusyMask        (  (0x8000 >> kPrinterBusyBit) )
  105. #define kHeadMovingMask            (  (0x8000 >> kHeadMovingBit) )
  106.  
  107. //<FF>
  108. /* ------------------------------------------------------------------------------------    */
  109. /*    INTERNAL ROUTINES                                                                */
  110. /* ------------------------------------------------------------------------------------    */
  111. void Long2Dec(long aLong, Ptr emitHere)
  112. /*
  113.     Converts a long into an ASCII string, padded with leading zeros.
  114. */
  115. {    
  116.     char    aString[10];
  117.     short    i, actualWidth, strLength;
  118.     
  119.     NumToString(aLong, (unsigned char *) aString);
  120.     
  121.     // Get the width of the string, check for being too small
  122.     strLength = aString[0];
  123.     actualWidth = strLength;
  124.     if (actualWidth < 4)
  125.         actualWidth = 4;
  126.         
  127.     // output the string, padding with the requested character
  128.     strLength = actualWidth-strLength;
  129.     for (i = 0; i < actualWidth; ++i)
  130.         {
  131.         *emitHere++ = (i < strLength) 
  132.             ? '0' : aString[(i+1)-(strLength)];
  133.         }
  134.         
  135. } // Long2Dec
  136.  
  137.  
  138. //<FF>
  139. /* ------------------------------------------------------------------------------------    */
  140. Boolean PrinterHasColorRibbon(gxPrinter thePrinter)
  141. /*
  142.     Returns true if the config file says that the printer is blessed with a color ribbon,
  143.     false if it is a black and white ribbon.
  144. */
  145. {
  146.     Boolean                        hasColor = true;
  147.     Str32                        deviceName;
  148.     OSErr                        anErr;
  149.     ImageWriterConfigHandle        configHandle;
  150.     
  151.     // if not formatting to a particular device, assume color ribbon, for widest range of colorSpaces
  152.     GXGetPrinterName(thePrinter, deviceName);
  153.     if (deviceName[0] != 0)
  154.         {
  155.         // if we are going to a particular device, assume no color, as that is more common
  156.         hasColor = false;
  157.         
  158.         anErr = GXFetchDTPData(deviceName, kImageWriterConfigType, kImageWriterConfigID, &(Handle)configHandle);
  159.         if (anErr == noErr)
  160.             {
  161.             hasColor = (**configHandle).hasColorRibbon;
  162.             DisposHandle((Handle) configHandle);
  163.             }
  164.         }
  165.     
  166.     return(hasColor);
  167.     
  168. } // PrinterHasColorRibbon
  169.  
  170.  
  171. //<FF>
  172. /* ------------------------------------------------------------------------------------    */
  173. gxViewDevice    NewDeviceResolutionViewDevice(void)
  174. /*
  175.     This routine creates a viewDevice and gives it a scale factor in it's mapping
  176.     appropriate for this device (144 dpi in the case of the IW)
  177. */
  178. {
  179.     gxViewDevice        vd;
  180.     
  181.     // create the viewDevices with a fake bitmap
  182.     {
  183.     gxShape        tempBitmap;
  184.     gxBitmap        aBitmap;
  185.     
  186.     aBitmap.pixelSize     = 1;
  187.     aBitmap.rowBytes     = 0;
  188.     aBitmap.width         = 0;
  189.     aBitmap.height         = 0;
  190.     aBitmap.image         = (char*)gxMissingImagePointer;
  191.     aBitmap.space         = gxNoSpace;
  192.     aBitmap.set         = nil;
  193.     aBitmap.profile     = nil;
  194.     
  195.     tempBitmap = GXNewBitmap(&aBitmap, nil);
  196.     vd = GXNewViewDevice(gxScreenViewDevices, tempBitmap);
  197.     GXDisposeShape(tempBitmap);
  198.     }
  199.  
  200.     // setup a mapping for a 144 (2X) viewDevice
  201.     {
  202.     gxMapping    vdMapping;
  203.     
  204.     ResetMapping(&vdMapping);
  205.     ScaleMapping(&vdMapping, ff(2), ff(2), ff(0), ff(0));
  206.     
  207.     GXSetViewDeviceMapping(vd, &vdMapping);
  208.     }
  209.     
  210.     return(vd);
  211.     
  212. } // NewDeviceResolutionViewDevice
  213.  
  214. //<FF>
  215. /* ------------------------------------------------------------------------------------    */
  216. Boolean    JobIsBest(long *imagewriterOptions)
  217. /*
  218.     Returns true if the current job is a final quality mode job, else returns false.
  219.     Also, returns the imagewriter rendering options.
  220. */
  221. {
  222.     Boolean            isFinal;
  223.     gxQualityInfo    jobQualitySettings;
  224.     long            itemSize = sizeof(jobQualitySettings);
  225.     OSErr            status;
  226.     Collection        jobCollection;
  227.     
  228.     // cache the collection
  229.     jobCollection = GXGetJobCollection(GXGetJob());
  230.     
  231.     // find out the info
  232.         
  233.     isFinal = false;
  234.     
  235.     status = GetCollectionItem(jobCollection, 
  236.                                     gxQualityTag, gxPrintingTagID, 
  237.                                     &itemSize, &jobQualitySettings);
  238.     
  239.     if ( (status == noErr) && (jobQualitySettings.currentQuality == (jobQualitySettings.qualityCount-1)) )
  240.         isFinal = true;
  241.     
  242.     ncheck( status );
  243.  
  244.     // we default to super res
  245.     *imagewriterOptions = kSuperRes;
  246.     itemSize = sizeof(imagewriterOptions);
  247.     status = GetCollectionItem(jobCollection, 
  248.                                     DriverCreator, 0, 
  249.                                     &itemSize, imagewriterOptions);
  250.                 
  251.     // and return the job quality mode
  252.     return(isFinal);
  253.     
  254. } // JobIsBest
  255.  
  256.  
  257. //<FF>
  258. /* ------------------------------------------------------------------------------------    */
  259.  
  260. OSErr    DoTheQuery(unsigned short * statusReturn, Boolean papStatus)
  261. /*
  262.     Returns in statusString the current status for the printer.  Returns various
  263.     errors from IO package if the printer's status could not be found.
  264. */
  265. {
  266.     OSErr                anErr = noErr;
  267.     long                statusLength;                    // status string size
  268.     SpecGlobalsHdl         hGlobals = GetMessageHandlerInstanceContext();
  269.  
  270.     // default to a clear status
  271.     *statusReturn = 0;
  272.  
  273.     // send the query
  274.     if (papStatus)
  275.         {
  276.         char    statusString[255];                // returned string
  277.         
  278.         // According to the old IW driver, sometimes it will return all of the bits
  279.         // set.  This is an error, but we can just try again.
  280.         do {
  281.             statusLength = 255;
  282.             anErr = Send_GXGetDeviceStatus(nil, 0, statusString, &statusLength, nil);
  283.             } while ( (anErr == noErr) && (statusString[0] == 0xFF) );
  284.         
  285.         // return the printer status bits in the PAP case
  286.         *statusReturn = *(unsigned short*)&statusString[0];
  287.         }
  288.     else
  289.         {
  290.         char    statusString[8];                // returned string
  291.  
  292.         if ((**hGlobals).isImageWriterII)
  293.             {
  294.             statusLength = 8; // max number of characters to get back
  295.             anErr = Send_GXGetDeviceStatus(kStatusCommand, 2, statusString, &statusLength, "\p\n");
  296.                 
  297.             if ( anErr == gxAioTimeout)
  298.                 {
  299.                 *statusReturn = kPrinterOfflineMask;
  300.                 anErr = noErr;
  301.                 }
  302.             else
  303.                 {
  304.                 if (anErr == noErr)
  305.                     {
  306.                     // generate printer status bits in the serial case
  307.                     if (statusString[4] == 'C')
  308.                         *statusReturn |= 0x8000 >> kColorRibbonBit;
  309.                     if ( (statusString[5] == 'F') || (statusString[4] == 'F') )
  310.                         *statusReturn |= 0x8000 >> kSheetFeederBit;
  311.                     }
  312.                 }
  313.             }
  314.         }
  315.         
  316.     nrequire(anErr, Send_GXGetDeviceStatus);
  317.  
  318. // FALL THROUGH EXCEPTION HANDLING    
  319. Send_GXGetDeviceStatus:
  320.     
  321.     return(anErr);
  322.  
  323. } // DoTheQuery
  324.  
  325. //<FF>
  326. /* ------------------------------------------------------------------------------------    */
  327. OSErr FetchStatusString(unsigned short * statusReturn, Boolean papStatus, Boolean doRetry)
  328. /*
  329.     Returns in statusString the current status for the printer.  Returns various
  330.     errors from IO package if the printer's status could not be found.
  331.     
  332.     Handles reporting error conditions to the user.
  333. */
  334. {
  335.     OSErr            anErr;
  336.     SpecGlobalsHdl         hGlobals = GetMessageHandlerInstanceContext();
  337.     
  338.     anErr = DoTheQuery(statusReturn, papStatus);        
  339.     nrequire(anErr, Send_GXGetDeviceStatus);
  340.     
  341.     // printer offline?
  342.     if (     
  343.         (doRetry) &&
  344.         ( ((*statusReturn) & kPrinterOfflineMask) != 0 )  
  345.         )
  346.         {
  347.         gxStatusRecord        theStat;
  348.         gxStatusRecord        *pStat = &theStat;
  349.         Boolean                printerIsFixed = false;
  350.         
  351.         pStat->statusOwner    = 'drvr';
  352.         pStat->statResId     = kDriverStatus;        
  353.         pStat->statResIndex = kCheckOnline;            
  354.         pStat->bufferLen      = 0;
  355.         pStat->dialogResult = 0;
  356.         
  357.  
  358.         // keep sending the user the alert until either
  359.         //  a) the problem resolves itself
  360.         //  b) the user responds via the dialog
  361.         //  c) some other (fatal) error happens
  362.         do
  363.             {
  364.             
  365.             // tell the user
  366.             anErr = GXAlertTheUser(pStat);
  367.             
  368.             // based on the user's response, continue or cancel
  369.             switch (pStat->dialogResult)
  370.                 {
  371.                 case ok:
  372.                     // retry
  373.                     break;
  374.                     
  375.                 case cancel:
  376.                     anErr = gxPrUserAbortErr;
  377.                     break;
  378.                     
  379.                 case 3:
  380.                     anErr = kPutJobOnHoldErr;
  381.                     break;
  382.                 }
  383.                 
  384.             // error to return from next idle
  385.             (**hGlobals).idleError = anErr;
  386.  
  387.             // if printer got suddenly turned online, do an OK
  388.             if ( (anErr == noErr) && ((papStatus) || (pStat->dialogResult == ok)) )
  389.                 {
  390.                 pStat->dialogResult = 0;
  391.                 (void) DoTheQuery(statusReturn, papStatus);        
  392.                 if (     
  393.                     ( ((*statusReturn) & kPrinterOfflineMask) == 0 ) 
  394.                     )
  395.                     {
  396.                     printerIsFixed = true;
  397.                     pStat->dialogResult = ok;
  398.                     anErr = noErr;
  399.                     }
  400.                 }
  401.                 
  402.             } while ((anErr == noErr) && (pStat->dialogResult == 0));
  403.  
  404.         // printer is okay -- no error
  405.         if (printerIsFixed)
  406.             anErr = noErr;
  407.         
  408.         // display "sending data to the printer" message
  409.         if (anErr == noErr)
  410.             anErr = GXReportStatus(kDriverStatus, kSendingData);
  411.         }
  412.  
  413. // FALL THROUGH EXCEPTION HANDLING    
  414. Send_GXGetDeviceStatus:
  415.     
  416.     return(anErr);
  417.     
  418. } // FetchStatusString
  419.  
  420. //<FF>
  421. /* ------------------------------------------------------------------------------------    */
  422. OSErr UpdateConfiguration(void)
  423. /*
  424.     This routine queries the printer for its hardware configuration (color ribbon and
  425.     sheet feeder options), and stores that info into the configuration file.
  426. */
  427. {
  428.     SpecGlobalsHdl                 hGlobals = GetMessageHandlerInstanceContext();
  429.     Str32                        deviceName;
  430.     OSErr                        anErr = noErr;
  431.     ImageWriterConfigHandle        configHandle;
  432.     ImageWriterConfigPtr        configPtr;
  433.     Boolean                        isImageWriterII = false;
  434.     ResType                        commType;
  435.     
  436.         
  437.     // find out what we are printing to, and how we are connected
  438.     GXGetPrinterName(GXGetJobOutputPrinter(GXGetJob()), deviceName);
  439.     anErr = GXFetchDTPData(deviceName, gxDeviceCommunicationsType, gxDeviceCommunicationsID, (Handle*)&configHandle);
  440.     nrequire(anErr, FetchCommType);
  441.     commType = **(ResType**)configHandle;
  442.     DisposHandle((Handle) configHandle);
  443.     
  444.     
  445.     // store away the communications type for future use
  446.     {
  447.     SpecGlobalsHdl             hGlobals = GetMessageHandlerInstanceContext();
  448.     
  449.     (**hGlobals).commType = commType;
  450.     }
  451.     
  452.     // find out the original configuration
  453.     if (GXFetchDTPData(deviceName, kImageWriterConfigType, kImageWriterConfigID, (Handle*)&configHandle) == noErr)
  454.         {
  455.         // remember if we thought we had an IW2 when we started
  456.         configPtr = *configHandle;
  457.         (**hGlobals).isImageWriterII = isImageWriterII = configPtr->isImageWriterII;
  458.         DisposeHandle((Handle) configHandle);
  459.  
  460.         // if we aren't an ImageWriter II, bail out now - because the timeout takes two minutes!
  461.         if (!isImageWriterII)
  462.             return(noErr);            
  463.         }
  464.     else
  465.         {        
  466.         // if we don't know yet, assume IW2 for PAP else Serial
  467.         if (commType == 'PPTL')
  468.             isImageWriterII = true;
  469.             
  470.         // Assume IW 2 so we do the query for real
  471.         (**hGlobals).isImageWriterII = true;
  472.         }
  473.         
  474.     // make a handle to hold our configuration information for the printer
  475.     configHandle = (ImageWriterConfigHandle) NewHandle(sizeof(ImageWriterConfigRecord) );
  476.     anErr = MemError();
  477.     nrequire(anErr, NewHandle);
  478.     
  479.     // setup the default for the device - in case the query fails
  480.     configPtr = *configHandle;
  481.     configPtr->hasColorRibbon = false;
  482.     configPtr->hasSheetFeeder = false;
  483.     configPtr->isImageWriterII = true;
  484.     
  485.     // send initial data first to make sure IO handshaking is working,
  486.     // to load the first sheet of paper into the feeder (if any),
  487.     // and to take up "gear lash" in the device.  This is copied from
  488.     // what the old driver did.  Not doing this will cause the sheet
  489.     // feeder not to feed the initial page of data.
  490.     {
  491.     char    sendBuffer[11];
  492.     
  493.     // <CR>
  494.     sendBuffer[0] = 0x0D;
  495.     
  496.     // linefeed size = 18/144th
  497.     sendBuffer[1] = ESCAPE;
  498.     sendBuffer[2] = 'T';
  499.     sendBuffer[3] = '1';
  500.     sendBuffer[4] = '8';
  501.     
  502.     // reverse line feed
  503.     sendBuffer[5] = ESCAPE;
  504.     sendBuffer[6] = 'r';
  505.     sendBuffer[7] = 0x0A;
  506.     
  507.     // forward line feed
  508.     sendBuffer[8] = ESCAPE;
  509.     sendBuffer[9] = 'f';
  510.     sendBuffer[10] = 0x0A;
  511.     
  512.     anErr = Send_GXWriteData(sendBuffer, 11);
  513.     nrequire(anErr, Failed_SendInitialData);
  514.     }
  515.     
  516.     {
  517.     unsigned short    statusReturn;
  518.     
  519.     // query the device
  520.     if ((isImageWriterII) && (commType == 'SPTL') )
  521.         (**hGlobals).idleTimeout = TickCount() + kQueryTimeout;
  522.     anErr = FetchStatusString(&statusReturn, (commType == 'PPTL'), isImageWriterII);
  523.     if ( (anErr == noErr) && ( (statusReturn & kPrinterOfflineMask) != 0 )  )
  524.         anErr = gxAioTimeout;
  525.     (**hGlobals).idleTimeout = 0;
  526.     (void) GXReportStatus(kDriverStatus, kSendingData);
  527.     
  528.     // and scan the string looking for information about printer kind and options
  529.     configPtr = *configHandle;
  530.     if ( anErr == gxAioTimeout )
  531.         {
  532.         // if we timeout and we don't know the printer kind - assume IW1
  533.         if (!isImageWriterII)
  534.             {
  535.             anErr = noErr;
  536.             isImageWriterII = configPtr->isImageWriterII = false;
  537.             }
  538.         }
  539.     else
  540.         {
  541.         isImageWriterII = true;
  542.         configPtr->hasColorRibbon = (statusReturn & (0x8000 >> kColorRibbonBit)) != 0;
  543.         configPtr->hasSheetFeeder = (statusReturn & (0x8000 >> kSheetFeederBit)) != 0;
  544.         }
  545.     nrequire(anErr, FetchStatusString);
  546.     }
  547.     
  548.     // Remember if this was an ImageWriter II after the query
  549.     (**hGlobals).isImageWriterII = isImageWriterII;
  550.     
  551.     // write out the new configuration
  552.     anErr = GXWriteDTPData(deviceName, kImageWriterConfigType, kImageWriterConfigID, (Handle)configHandle);
  553.     
  554.     
  555. // CLEANUP EXCEPTION HANDLING
  556. FetchStatusString:
  557. Failed_SendInitialData:
  558.     DisposHandle((Handle) configHandle);
  559.     
  560. NewHandle:
  561. Send_GXWriteData:
  562. FetchCommType:
  563.     return(anErr);
  564.     
  565. } // UpdateConfiguration
  566.  
  567.  
  568. /* ------------------------------------------------------------------------------------    */
  569. OSErr WriteDraftChars(long **draftTable, unsigned char *draftChar, long numChars)
  570. /*
  571.     This routine writes out a single character in the native set of the printer.
  572.     It uses a table that's part of the driver to do the right thing in order to generate this
  573.     character.
  574. */
  575. {
  576.     OSErr        anErr = noErr;
  577.     char        outputChars[20];                // a maximum of 20 characters can be generated
  578.     short        charCount;                    
  579.     
  580.     // For each character in the buffer, determine how to map the character to a draft character
  581.     for (; numChars > 0; --numChars, ++draftChar)
  582.     {
  583.         // No characters yet for this output character
  584.         charCount = 0;
  585.             
  586.         // Only consider characters in the printable range
  587.         if (*draftChar >= 0x20)
  588.         {
  589.             unsigned long    draftControl = (*draftTable)[*draftChar-0x20];    // Fetch native mode long word corresponding to this character
  590.             unsigned char    outChar;
  591.             unsigned char    nationalSet;
  592.             short                i;
  593.             
  594.             // For each word which composes the native mode long word 
  595.             for (i = 1; i >= 0; --i)
  596.             {
  597.                 // Should we send a backspace character (to overstrike)?
  598.                 if ( (draftControl & 0x80000000) != 0 )
  599.                     outputChars[charCount++] = 0x08;
  600.                 
  601.                 outChar = (draftControl >> 16) & 0xFF;
  602.                 if (outChar != 0)
  603.                 {
  604.                     // Determine the national character set to select
  605.                     nationalSet = (draftControl >> 24) & 0xF;    
  606.     
  607.                     //    Is this character in the standard, built-in character set?
  608.                     if (nationalSet == 0)
  609.                     {
  610.                         outputChars[charCount++] = outChar;
  611.                     }
  612.                     else    //    T => Must select a foreign language character set 
  613.                     {
  614.                         outputChars[charCount++] = 0x1B;
  615.                         outputChars[charCount++] = 0x44;
  616.                         outputChars[charCount++] = nationalSet;
  617.                         outputChars[charCount++] = 0x00;
  618.                         outputChars[charCount++] = outChar;
  619.                         outputChars[charCount++] = 0x1B;                // We always switch back to the kAmerican character set
  620.                         outputChars[charCount++] = 0x5A;
  621.                         outputChars[charCount++] = 0x07;
  622.                         outputChars[charCount++] = 0x00;
  623.                     }
  624.                 }
  625.                 
  626.                 // Take the next (low) word and process it (if we're not all done)
  627.                 draftControl <<= 16;
  628.             }    
  629.         }
  630.             
  631.         // If we generated any data, send it out now
  632.         if (charCount > 0)
  633.             anErr = Send_GXBufferData(outputChars, charCount, gxNoBufferOptions);
  634.     }
  635.         
  636.     return(anErr);    
  637.     
  638. } // WriteDraftChars
  639.  
  640. /* ------------------------------------------------------------------------------------    */
  641. OSErr GetPointerThisBig(Ptr *theBuff, long numBytes) 
  642. {
  643.     OSErr        anErr = noErr;
  644.     
  645.     if (*theBuff != nil)
  646.     {
  647.         if ( GetPtrSize(*theBuff) < numBytes )    //    T => Won't be big enough; make a new one
  648.         {
  649.             DisposPtr(*theBuff);
  650.             *theBuff = nil;
  651.         }
  652.     }
  653.  
  654.     if (*theBuff == nil)
  655.     {
  656.         *theBuff = NewPtrClear(numBytes);
  657.         anErr = MemError();
  658.     }
  659.     
  660.     return(anErr);
  661.     
  662. } // GetPointerThisBig
  663.  
  664. /* ------------------------------------------------------------------------------------    */
  665. OSErr GetTextAndPosition(    gxShape            theShape, 
  666.                             Ptr                *theChars, 
  667.                             long            *numChars, 
  668.                             gxPoint            *textPosition)
  669. {
  670.     OSErr        anErr = noErr;
  671.     long        textLength;
  672.     
  673.     // Determine the size of the text data and the position of the text
  674.     textLength = GXGetLayout(theShape, nil, nil, nil, nil, nil, nil, nil, nil, textPosition);
  675.  
  676.     // Make sure we have a buffer pointer large enough to hold all of the data
  677.     
  678.     anErr = GetPointerThisBig(theChars, textLength);
  679.     require(anErr == noErr, CantAllocTextBuff);
  680.     
  681.     // Now we retrieve the text
  682.     GXGetLayout(theShape, *theChars, nil, nil, nil, nil, nil, nil, nil, nil);
  683.     
  684.     // Remember the number of characters in the shape
  685.     *numChars = textLength;
  686.     
  687.  
  688. /******* Clean-up *******/
  689.  
  690. CantAllocTextBuff:
  691.     return(anErr);
  692.     
  693. } // GetTextAndPosition
  694.  
  695. /* ------------------------------------------------------------------------------------    */
  696. OSErr PrintPageInDraftMode(gxShape thePage, gxRasterImageDataHdl imageData)
  697. {
  698.     OSErr                    anErr = noErr;
  699.     long                    i;
  700.     long                    numItems;
  701.     Fixed                    currYPos = ff(0);
  702.     Ptr                        theChars = nil;
  703.     long                    numChars = 0;
  704.     gxPoint                    textPosition;
  705.     Fixed                    oldTextSize = ff(0);
  706.     SpecGlobalsHdl             hGlobals = GetMessageHandlerInstanceContext();
  707.     
  708.     // Since the page picture we need to process is a picture shape that's embedded in
  709.     // thePage (a shape containing one item => a picture), we need to extract the real
  710.     // page picture from thePage.
  711.  
  712.     
  713.     thePage = GetPictureItem(thePage, 1, nil, nil, nil, nil);
  714.     numItems = GXGetPicture(thePage, nil, nil, nil, nil);
  715.     
  716.     // For each shape within the picture, check its type and process it accordingly
  717.     
  718.     for (i = 1; i <= numItems; ++i)
  719.     {
  720.         gxShape                theShape;
  721.         short                theType;
  722.                 
  723.         theShape = GetPictureItem(thePage, i, nil, nil, nil, nil);
  724.         theType = GXGetShapeType(theShape);
  725.         
  726.         if (theType == gxLayoutType)    //    T => We have a layout shape
  727.         {
  728.             Fixed        textSize;
  729.             char        buff[12];
  730.             char        theFace;
  731.             short        cmndBuffSz;
  732.             
  733.             // First determine the style in which we're printing
  734.             
  735.             theFace = GetStyleCommonFace( GXGetShapeStyle(theShape) );
  736.             
  737.             buff[0] = ESCAPE;
  738.             if ( (theFace & bold) != 0 )    //    T => Turn bold facing on
  739.                 buff[1] = '!';
  740.             else                                    //    T => Turn it off
  741.                 buff[1] = '"';
  742.             
  743.             buff[2] = ESCAPE;
  744.             if ( (theFace & underline) != 0 )    //    T => Turn underline facing on
  745.                 buff[3] = 'X';
  746.             else                                            //    T => Turn it off
  747.                 buff[3] = 'Y';
  748.                 
  749.             cmndBuffSz = 4;
  750.             
  751.             // Next determine if we need to change the size of the font being used
  752.             
  753.             textSize = GXGetShapeTextSize(theShape);
  754.             if (textSize != oldTextSize)    //    T => Must issue LQ command to change font size
  755.             {
  756.                 buff[4] = ESCAPE;                //    The first escape command selects black color
  757.                 buff[5] = kSetColorCommand;
  758.                 buff[6] = '0';
  759.                 
  760.                 buff[7] = ESCAPE;                //    The second escape command selects a draft font
  761.                 buff[8] = 'a';
  762.                 buff[9] = '1';
  763.                 
  764.                 buff[10] = ESCAPE;                //    The third escape command selects the character pitch
  765.                 
  766.                 if ( textSize <= ff(10) )    //    T => Select 10 cpi
  767.                 {
  768.                     buff[11] = 'N';
  769.                 }
  770.                 else    //    T => All other sizes get mapped to 12 cpi
  771.                 {
  772.                     buff[11] = 'E';
  773.                 }
  774.                 
  775.                 // Remember the last text size
  776.                 oldTextSize = textSize;    
  777.                 
  778.                 // Adjust the size of the data to be sent to the printer
  779.                 cmndBuffSz += 8;
  780.             }
  781.             // else - no change in font size
  782.             
  783.             // Send the commands to the printer
  784.             anErr = Send_GXBufferData(buff, cmndBuffSz, gxDontSplitBuffer);
  785.             require(anErr == noErr, CantSendFontCmnd);
  786.  
  787.             // Get the ASCII text and the starting position of the data
  788.             anErr = GetTextAndPosition(theShape, &theChars, &numChars, &textPosition);
  789.             require(anErr == noErr, CantGetTextAndPos);
  790.             
  791.             if ( (currYPos != ff(0)) && (currYPos != textPosition.y) )    //    T => Moving to a lower line, finish the last ;line with a CR
  792.             {
  793.                 char        c = 0x0D;
  794.                 
  795.                 anErr = Send_GXBufferData(&c, 1, gxNoBufferOptions);
  796.                 require(anErr == noErr, CantSendCRCmnd);
  797.             }
  798.             
  799.             // Position the print head to the proper location on the page
  800.             {
  801.                 gxMapping                theMapping;
  802.                 long                    lineFeedSize;
  803.                 Str255                    positionCmndsBuff;
  804.                 unsigned long            bytesInBuff = 0;
  805.                 char                    *p;
  806.  
  807.                 GXGetShapeMapping(theShape, &theMapping);
  808.                 MapPoints(&theMapping, (long) 1, &textPosition);    //    Just map the first point
  809.                 
  810.                 // Now position the print head vertically
  811.  
  812.                 lineFeedSize = (textPosition.y - currYPos) >> 16;
  813.                 anErr = Send_GXRasterLineFeed(&lineFeedSize, (char *) positionCmndsBuff, &bytesInBuff, imageData);
  814.                 require(anErr == noErr, CantEmitLineFeeds);
  815.                 
  816.                 // Update the current Y position pointer on the page
  817.                 currYPos = textPosition.y;
  818.  
  819.                 // Now position the print head horizontally on the page
  820.  
  821.                 p = (char *) &positionCmndsBuff[bytesInBuff];        
  822.                 *p++ = ESCAPE;
  823.                 *p++ = 'F';
  824.                 Long2Dec((*hGlobals)->leftMargin + FixedToInt(textPosition.x), p);    // Convert left margin into ASCII and place it at the start of the scan line
  825.                 
  826.                 // Update the number of bytes in the buffer
  827.                 bytesInBuff += 6;
  828.  
  829.                 // Send the positioning info to the printer
  830.                 anErr = Send_GXBufferData((char *) positionCmndsBuff, bytesInBuff, gxDontSplitBuffer);
  831.                 require(anErr == noErr, CantSendPositionCmnds);
  832.             }
  833.             
  834.             // Now we send the text data to the printer
  835.             anErr = WriteDraftChars((long **) (*hGlobals)->draftTable, (unsigned char *) theChars, numChars);
  836.             require(anErr == noErr, CantWriteChars);
  837.         }
  838.     }    // for
  839.  
  840.     // Send one last CR to wrap the last line (if there was one)
  841.     {
  842.         char        c = 0x0D;
  843.         
  844.         anErr = Send_GXBufferData(&c, 1, gxNoBufferOptions);
  845.     }
  846.  
  847.  
  848. /******* Clean-up *******/
  849.  
  850. CantWriteChars:
  851. CantSendPositionCmnds:
  852. CantEmitLineFeeds:
  853. CantSendCRCmnd:
  854. CantGetTextAndPos:
  855. CantSendFontCmnd:
  856.     if (theChars != nil)
  857.         DisposPtr(theChars);
  858.                 
  859.     return(anErr);
  860.     
  861. } // PrintPageInDraftMode 
  862.  
  863. //<FF>
  864. /* ------------------------------------------------------------------------------------    */
  865. /*    SPECIFIC DRIVER UNIVERSAL OVERRIDES                                                    */
  866. /* ------------------------------------------------------------------------------------    */
  867. OSErr SD_Initialize (void) 
  868. /*
  869.     The SD_Initalize message is called when a new job is created.  The standard
  870.     thing to do is to allocate and fill out your globals as you see fit.
  871. */
  872. {
  873.  
  874.     SpecGlobalsHdl     hGlobals;
  875.     OSErr             anErr;
  876.         
  877.     // we make our globals
  878.     hGlobals = (SpecGlobalsHdl) NewHandleClear( sizeof(SpecGlobals) );
  879.     anErr = MemError();
  880.  
  881.     // and we save them away
  882.     SetMessageHandlerInstanceContext(hGlobals);
  883.  
  884.     // is everything okay?
  885.     nrequire(anErr, MNewHandleClear);
  886.     
  887.     // Don't need to initialize because of the NewHandleCLEAR
  888.     //(**hGlobals).draftTable = nil;
  889.     //(**hGlobals).lineFeeds = 0;
  890.     //(**hGlobals).packagingOptions = kNoPackagingOptions;
  891.     //(**hGlobals).idleError         = noErr;
  892.     //(**hGlobals).idleQuery         = false;
  893.     //(**hGlobals).idleTimeout         = 0;
  894.     //(**hGlobals).timeoutPending     = false;
  895.     
  896.     
  897.     return(noErr);
  898.     
  899.     
  900. /*-----EXCEPTION HANDLING------*/
  901.  
  902.  
  903. MNewHandleClear:
  904.     return(anErr);
  905.     
  906. } // SD_Initialize
  907.  
  908.  
  909. //<FF>
  910. /* ------------------------------------------------------------------------------------    */
  911. OSErr SD_ShutDown(void) 
  912. /*
  913.     Shutdown is called when the job is done with.  A good thing to do is to get
  914.     rid of any additional storage that is laying around.
  915. */
  916. {
  917.     // clean up our stuff
  918.     SpecGlobalsHdl hGlobals = GetMessageHandlerInstanceContext();
  919.  
  920.     // get rid of the draft table (if we have one)
  921.     if (hGlobals)
  922.         DisposHandle((**hGlobals).draftTable);
  923.     
  924.     // we get rid of our storage
  925.     DisposHandle((Handle) hGlobals);
  926.     
  927.     // clear out our globals - to avoid double disposes
  928.     SetMessageHandlerInstanceContext(nil);
  929.  
  930.     return(noErr);
  931.     
  932.     
  933. } // SD_ShutDown
  934.  
  935. //<FF>
  936. /* ------------------------------------------------------------------------------------    */
  937. OSErr    SD_DefaultPrinter(gxPrinter thePrinter)
  938. /*
  939.     This call is made to setup the default printer object.  The job of the
  940.     specific driver is to add in any viewDevices that it wishes applications
  941.     to be able to format specifically for.
  942. */
  943. {
  944.     OSErr            anErr;
  945.     gxViewDevice    vd;
  946.     gxJob            theJob = GXGetJob();
  947.     
  948.     // add the standard viewDevices first
  949.     anErr = Forward_GXDefaultPrinter(thePrinter);
  950.     nrequire(anErr, DefaultPrinter);
  951.     
  952.     // add a 144 b/w viewDevice
  953.     vd = NewDeviceResolutionViewDevice();
  954.     {
  955.     gxSetColor        theColors[2];
  956.     gxSetColor        *pColor;
  957.     gxColorSet        theSet;
  958.     
  959.     pColor = &theColors[0];
  960.     
  961.     pColor->rgb.red = pColor->rgb.green = pColor->rgb.blue = 0xFFFF;
  962.     
  963.     pColor++;
  964.     pColor->rgb.red = pColor->rgb.green = pColor->rgb.blue = 0x0000;
  965.     
  966.     theSet = GXNewColorSet(gxRGBSpace, 2, theColors);
  967.     SetViewDeviceColorSet(vd, theSet);
  968.     GXDisposeColorSet(theSet);
  969.     }
  970.         
  971.     anErr = GXAddPrinterViewDevice(thePrinter, vd);
  972.     nrequire(anErr, FailedAddBWViewDevice);
  973.  
  974.     
  975.     // add a 144 color viewDevice with 8 colors in it
  976.     //
  977.     //    Color        Index        R            G            B
  978.     //    white        0            0xFFFF        0xFFFF        0xFFFF        
  979.     //    yellow        1            0xFFFF        0xFFFF        0x0000
  980.     //    magenta        2            0xFFFF        0x0000        0xFFFF
  981.     //    red            3            0xFFFF        0x0000        0x0000
  982.     //    cyan        4            0x0000        0xFFFF        0xFFFF
  983.     //    green        5            0x0000        0xFFFF        0x0000
  984.     //    blue        6            0x0000        0x0000        0xFFFF
  985.     //    black        7            0x0000        0x0000        0x0000
  986.     
  987.     if (PrinterHasColorRibbon(thePrinter))
  988.         {
  989.         gxSetColor        theColors[8];
  990.         gxSetColor        *pColor;
  991.         gxColorSet        theSet;
  992.         short            idx;
  993.  
  994.         vd = NewDeviceResolutionViewDevice();
  995.         
  996.         pColor = &theColors[0];
  997.         for (idx = 0; idx < 8; ++idx)
  998.             {
  999.             // default the color to black
  1000.             pColor->rgb.red = pColor->rgb.green = pColor->rgb.blue = 0x0000;
  1001.             
  1002.             // and give it componants to go along with this index
  1003.             if (idx & 0x04)
  1004.                 pColor->rgb.red     = 0xFFFF;
  1005.             if (idx & 0x02)
  1006.                 pColor->rgb.green     = 0xFFFF;
  1007.             if (idx & 0x01)
  1008.                 pColor->rgb.blue     = 0xFFFF;
  1009.                 
  1010.             // move on to the next color
  1011.             ++pColor;
  1012.             }
  1013.         
  1014.         theSet = GXNewColorSet(gxRGBSpace, 8, theColors);
  1015.         SetViewDeviceColorSet(vd, theSet);
  1016.         GXDisposeColorSet(theSet);
  1017.  
  1018.         anErr = GXAddPrinterViewDevice(thePrinter, vd);
  1019.         nrequire(anErr, FailedAddColorViewDevice);
  1020.         }
  1021.     
  1022.     /* Only if we are the output printer (not the formatting printer) */
  1023.     if (GXGetJobPrinter(theJob) == GXGetJobOutputPrinter(theJob)) {
  1024.         Collection            jobCollection = GXGetJobCollection(GXGetJob());
  1025.         Handle                 jobQualitySettingsHdl;    
  1026.         gxQualityInfo        *qualitySettings;
  1027.         Ptr                    p;
  1028.         Str255                bestString, roughString;
  1029.  
  1030.         // read in our quality mode strings
  1031.         {
  1032.         short    curResFile = CurResFile();
  1033.         
  1034.         UseResFile(GXGetMessageHandlerResFile());
  1035.         
  1036.         GetIndString( bestString, kNewQualityID, kBestString);
  1037.         GetIndString( roughString, kNewQualityID, kRoughString);
  1038.         UseResFile(curResFile);
  1039.         }
  1040.         
  1041.         jobQualitySettingsHdl = NewHandle(0);
  1042.         anErr = MemError();
  1043.         nrequire(anErr, FailedNewHandle);
  1044.  
  1045.         anErr = GetCollectionItemHdl (     jobCollection,
  1046.                                         gxQualityTag,
  1047.                                         gxPrintingTagID,
  1048.                                         jobQualitySettingsHdl );
  1049.  
  1050.         if (anErr == noErr) 
  1051.             {    /* Check for proper structure -- count as not found if different */
  1052.             HLockHi(jobQualitySettingsHdl);
  1053.  
  1054.             qualitySettings = *((gxQualityInfo **) jobQualitySettingsHdl);
  1055.             p = qualitySettings->qualityNames;
  1056.  
  1057.             if (qualitySettings->disableQuality) 
  1058.                 anErr = collectionItemNotFoundErr;
  1059.             else if (qualitySettings->qualityCount != 2)
  1060.                 anErr = collectionItemNotFoundErr;
  1061.             else if (! IUEqualString((unsigned char const *) p, bestString))
  1062.                 anErr = collectionItemNotFoundErr;
  1063.             else if (! IUEqualString((unsigned char const *) (p + p[0] + 1), roughString))
  1064.                 anErr = collectionItemNotFoundErr;
  1065.  
  1066.             HUnlock(jobQualitySettingsHdl);
  1067.             }
  1068.  
  1069.         if (anErr == collectionItemNotFoundErr) 
  1070.             {
  1071.             Size            count;
  1072.  
  1073.             /* Create the proper quality item */
  1074.             SetHandleSize(jobQualitySettingsHdl,(sizeof(gxQualityInfo) + bestString[0] + roughString[0] + 2 ));
  1075.             anErr = MemError();
  1076.             nrequire( anErr, FailedSetHandleSize );
  1077.                 
  1078.             qualitySettings = *((gxQualityInfo **) jobQualitySettingsHdl);
  1079.             
  1080.             qualitySettings->disableQuality = false;
  1081.             qualitySettings->defaultQuality = 1;
  1082.             qualitySettings->currentQuality = 1;
  1083.             qualitySettings->qualityCount = 2;
  1084.  
  1085.             count = bestString[0]+1;
  1086.             p = qualitySettings->qualityNames;
  1087.             BlockMove( bestString, p, count );
  1088.  
  1089.             p += count;
  1090.             BlockMove( roughString, p, roughString[0]+1 );
  1091.  
  1092.             /* Add the proper quality item */
  1093.             anErr = AddCollectionItemHdl (     jobCollection,
  1094.                                             gxQualityTag,
  1095.                                             gxPrintingTagID,
  1096.                                             jobQualitySettingsHdl );
  1097.  
  1098.             /* Make it vilatile by driver */
  1099.             if (anErr == noErr)
  1100.                 (void) SetCollectionItemInfo(jobCollection, gxQualityTag, gxPrintingTagID, 0x0000FFFF, gxVolatileOutputDriverCategory);
  1101.  
  1102.             }
  1103.         
  1104. FailedSetHandleSize:
  1105.         DisposHandle(jobQualitySettingsHdl);
  1106.     }
  1107. FailedNewHandle:
  1108.     
  1109.     ncheck(noErr);
  1110.     return(noErr);
  1111.     
  1112.     
  1113.     
  1114. // EXCEPTION HANDLING
  1115. FailedAddColorViewDevice:
  1116. FailedAddBWViewDevice:
  1117.     GXDisposeViewDevice(vd);
  1118.     
  1119. DefaultPrinter:
  1120.     return(anErr);
  1121.     
  1122. } // SD_DefaultPrinter
  1123.  
  1124. //<FF>
  1125. /* ------------------------------------------------------------------------------------    */
  1126.  
  1127. OSErr SD_DefaultFormat(gxFormat theFormat)
  1128. {
  1129.     OSErr                anErr;
  1130.     Handle                 jobQualitySettingsHdl;    
  1131.     
  1132.     anErr = Forward_GXDefaultFormat(theFormat);
  1133.     
  1134.     // now, if the application has set up a special formatting mode, we need to update
  1135.     // the quality mode collection item (and any private ones we use)
  1136.     if (anErr == noErr)
  1137.         {
  1138.         gxPoint                dpiPoint;
  1139.         gxMapping            vdMapping;
  1140.         gxViewDevice        selectedDevice = GXGetPrinterViewDevice(GXGetJobPrinter(GXGetFormatJob(theFormat)), 0);
  1141.         
  1142.         
  1143.         dpiPoint.x = ff(72);
  1144.         dpiPoint.y = ff(72);
  1145.         
  1146.         if (selectedDevice != GXGetPrinterViewDevice(GXGetJobPrinter(GXGetFormatJob(theFormat)), 1) )
  1147.             {
  1148.             GXGetViewDeviceMapping(selectedDevice, &vdMapping);
  1149.             MapPoints(&vdMapping, 1, &dpiPoint);
  1150.             
  1151.             {
  1152.             Collection            jobCollection = GXGetJobCollection(GXGetJob());
  1153.             gxQualityInfo        *qualitySettings;
  1154.     
  1155.             jobQualitySettingsHdl = NewHandle(0);
  1156.             anErr = MemError();
  1157.             nrequire(anErr, FailedNewHandle);
  1158.  
  1159.             anErr = GetCollectionItemHdl (     jobCollection,
  1160.                                                 gxQualityTag,
  1161.                                                  gxPrintingTagID,
  1162.                                                jobQualitySettingsHdl );
  1163.  
  1164.             nrequire(anErr, FailedGetCollectionItemHdl);
  1165.  
  1166.             qualitySettings = *((gxQualityInfo **) jobQualitySettingsHdl);
  1167.  
  1168.             qualitySettings->currentQuality = 
  1169.                 (dpiPoint.y > ff(100)) ? (qualitySettings->qualityCount-1) : 0;
  1170.  
  1171.             anErr = AddCollectionItemHdl (     jobCollection,
  1172.                                             gxQualityTag,
  1173.                                             gxPrintingTagID,
  1174.                                             jobQualitySettingsHdl );
  1175.                                                  
  1176.             DisposHandle(jobQualitySettingsHdl);
  1177.             }
  1178.  
  1179.         
  1180.             if (anErr == noErr)
  1181.                 {
  1182.                 long    formatOptions;
  1183.                 
  1184.                 // turn off super-res
  1185.                 formatOptions = 0;
  1186.                 anErr = AddCollectionItem(GXGetFormatCollection(theFormat), 
  1187.                     DriverCreator, 0,
  1188.                     sizeof(formatOptions),
  1189.                     &formatOptions);
  1190.                 }
  1191.             }
  1192.         }
  1193.  
  1194. FailedNewHandle:        
  1195.     ncheck(anErr);
  1196.     return(anErr);
  1197.  
  1198. FailedGetCollectionItemHdl:
  1199.     DisposHandle(jobQualitySettingsHdl);
  1200.     return(anErr);
  1201.     
  1202. } // SD_DefaultFormat
  1203.  
  1204. //<FF>
  1205. /* ------------------------------------------------------------------------------------    */
  1206. OSErr SD_DefaultJob()
  1207. /*
  1208.     We override this message to add our default - highest res possible
  1209. */
  1210. {
  1211.     OSErr    anErr;
  1212.     
  1213.     anErr = Forward_GXDefaultJob();
  1214.     if (anErr == noErr)
  1215.         {
  1216.         long        imagewriterOptions = kSuperRes;
  1217.         
  1218.         anErr = AddCollectionItem(GXGetJobCollection(GXGetJob()), 
  1219.                     DriverCreator,
  1220.                     0,
  1221.                     sizeof(imagewriterOptions),
  1222.                     &imagewriterOptions);
  1223.                     
  1224.         }
  1225.  
  1226.  
  1227.     return(anErr);
  1228.     
  1229. } // SD_DefaultJob
  1230.  
  1231. /* ------------------------------------------------------------------------------------    */
  1232. OSErr SD_OpenConnection(void)
  1233. /*
  1234.     The OpenConnection message is sent in order to open the connection to the device.
  1235. */
  1236. {
  1237.     OSErr    anErr;
  1238.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1239.     
  1240.     // how to process idle events
  1241.     (**hGlobals).idleError         = noErr;
  1242.     (**hGlobals).idleQuery         = false;
  1243.     (**hGlobals).idleTimeout     = 0;
  1244.     (**hGlobals).timeoutPending = false;
  1245.     
  1246.     // first, open the connection the standard way
  1247.     anErr = Forward_GXOpenConnection();
  1248.     nrequire(anErr, OpenConnection);
  1249.     
  1250.     // then, bring the configuration file up to date
  1251.     anErr = UpdateConfiguration();
  1252.     nrequire(anErr, UpdateConfiguration);
  1253.     
  1254.     return(noErr);
  1255.     
  1256. // EXCEPTION HANDLING
  1257. UpdateConfiguration:
  1258.     GXCleanupOpenConnection();
  1259.     
  1260. OpenConnection:
  1261.  
  1262.     return(anErr);
  1263.     
  1264. } // SD_OpenConnection
  1265.  
  1266. /* ------------------------------------------------------------------------------------    */
  1267. OSErr SD_CloseConnection(void)
  1268. {
  1269.     unsigned short    statusReturn;
  1270.     OSErr            anErr, anErr2;
  1271.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1272.     ResType            commType = (**hGlobals).commType;
  1273.  
  1274.     if (commType == 'PPTL')
  1275.         {
  1276.         // flush out all data so that we can query the printer properly    one last time
  1277.         anErr = Send_GXWriteData(nil, 0);
  1278.         nrequire(anErr, Send_GXWriteData1);
  1279.         
  1280.         // for PAP: bring the configuration file up to date & check that the printer is online
  1281.         anErr2 = UpdateConfiguration();
  1282.         if (anErr == noErr) anErr = anErr2;
  1283.         }
  1284.     else
  1285.         {
  1286.         // for serial: flush out all data so that we can query the printer properly    one last time
  1287.         anErr = Send_GXWriteData(nil, 0);
  1288.         nrequire(anErr, Send_GXWriteData2);
  1289.  
  1290.         // one last time check up on printer status 
  1291.         if ((**hGlobals).isImageWriterII)
  1292.             {
  1293.             anErr2 = FetchStatusString(&statusReturn, false, true);
  1294.             if (anErr == noErr) anErr = anErr2;
  1295.             }
  1296.         }
  1297.     
  1298. Send_GXWriteData2:
  1299. Send_GXWriteData1:
  1300. FetchStatusString:
  1301.     // close the connection the standard way
  1302.     anErr2 = Forward_GXCloseConnection();
  1303.     if (anErr == noErr) anErr = anErr2;
  1304.         
  1305.     return(anErr);
  1306.     
  1307. } // SD_CloseConnection
  1308.  
  1309. /* ------------------------------------------------------------------------------------    */
  1310. OSErr SD_JobIdle()
  1311. {
  1312.     OSErr            anErr = noErr;
  1313.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1314.     SpecGlobalsPtr    pGlobals;
  1315.     
  1316.     pGlobals = *hGlobals;
  1317.     if ( (pGlobals->idleQuery) && (pGlobals->commType == 'PPTL') )
  1318.         {
  1319.         unsigned short    statusReturn;
  1320.  
  1321.         pGlobals->idleQuery = false;
  1322.         
  1323.         anErr = FetchStatusString(&statusReturn, true, true);
  1324.         nrequire(anErr, FetchStatusString);
  1325.  
  1326.         anErr = Forward_GXJobIdle();
  1327.  
  1328.         // EXCEPTION HANDLING
  1329.         FetchStatusString:
  1330.             pGlobals = *hGlobals;
  1331.             pGlobals->idleQuery = true;
  1332.         }
  1333.     else    
  1334.         anErr = Forward_GXJobIdle();
  1335.     
  1336.     // if we continue looping here too long during the initial query -- give the user
  1337.     // a chance to bail or correct the problem
  1338.     pGlobals = *hGlobals;
  1339.     if ( (!(pGlobals->timeoutPending)) && (pGlobals->idleTimeout != 0) )
  1340.         {
  1341.         if (TickCount() > pGlobals->idleTimeout)
  1342.             {
  1343.             gxStatusRecord        theStat;
  1344.             gxStatusRecord        *pStat = &theStat;
  1345.             
  1346.             pStat->statusOwner    = 'drvr';
  1347.             pStat->statResId     = kDriverStatus;        
  1348.             pStat->statResIndex = kCheckOnline;            
  1349.             pStat->bufferLen      = 0;
  1350.             pStat->dialogResult = 0;
  1351.                         
  1352.             // tell the user to check the printer
  1353.             pGlobals->timeoutPending = true;
  1354.             (void) GXAlertTheUser(pStat);
  1355.             pGlobals = *hGlobals;
  1356.             pGlobals->timeoutPending = false;
  1357.                 
  1358.             // based on the user's response cancel
  1359.             switch (pStat->dialogResult)
  1360.                 {
  1361.                 case ok:
  1362.                     pGlobals->idleTimeout = TickCount() + kQueryTimeout;
  1363.                     break;
  1364.                     
  1365.                 case cancel:
  1366.                     pGlobals->idleError = gxPrUserAbortErr;
  1367.                     break;
  1368.                     
  1369.                 case 3:
  1370.                     pGlobals->idleError = kPutJobOnHoldErr;
  1371.                     break;
  1372.                 }
  1373.  
  1374.             // display "sending data to the printer" message
  1375.             if (anErr == noErr)
  1376.                 anErr = GXReportStatus(kDriverStatus, kSendingData);
  1377.             }
  1378.         }
  1379.         
  1380.     if (anErr == noErr)
  1381.         anErr = pGlobals->idleError;
  1382.         
  1383.     return(anErr);
  1384.     
  1385. } // SD_JobIdle
  1386.  
  1387. /* ------------------------------------------------------------------------------------    */
  1388. OSErr SD_FreeBuffer(gxPrintingBuffer * theBuffer)
  1389. {
  1390.     OSErr            anErr = noErr;
  1391.     OSErr            firstError = noErr;
  1392.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1393.     
  1394.  
  1395.     if ((**hGlobals).commType == 'PPTL')
  1396.         {
  1397.         unsigned short    statusReturn;
  1398.  
  1399.         anErr = FetchStatusString(&statusReturn, true, true);
  1400.         nrequire(anErr, FetchStatusString);
  1401.         }
  1402.         
  1403.     do
  1404.         {
  1405.         // we can idle query now if we need to    
  1406.         (**hGlobals).idleQuery = true;
  1407.  
  1408.         // try to send the buffer again
  1409.         anErr = Forward_GXFreeBuffer(theBuffer);
  1410.         if (firstError == noErr)
  1411.             firstError = anErr;
  1412.     
  1413.         (**hGlobals).idleQuery = false;
  1414.  
  1415.         // timeout dialog!
  1416.         if (anErr == gxAioTimeout)
  1417.             {
  1418.             gxStatusRecord        theStat;
  1419.             gxStatusRecord        *pStat = &theStat;
  1420.             
  1421.             pStat->statusOwner    = 'drvr';
  1422.             pStat->statResId     = kDriverStatus;        
  1423.             pStat->statResIndex = kCheckOnline;            
  1424.             pStat->bufferLen      = 0;
  1425.             pStat->dialogResult = 0;
  1426.                         
  1427.             // tell the user to check the printer
  1428.             (void) GXAlertTheUser(pStat);
  1429.                 
  1430.             // based on the user's response cancel
  1431.             switch (pStat->dialogResult)
  1432.                 {
  1433.                 case ok:
  1434.                     anErr = gxAioTimeout;
  1435.                     break;
  1436.                     
  1437.                 case cancel:
  1438.                     anErr = gxPrUserAbortErr;
  1439.                     break;
  1440.                     
  1441.                 case 3:
  1442.                     anErr = kPutJobOnHoldErr;
  1443.                     break;
  1444.                 }
  1445.             }
  1446.             
  1447.         } while (anErr == gxAioTimeout);
  1448.     
  1449.     // put down the timeout dialog, if we ever put one up
  1450.     if (firstError != noErr)
  1451.         (void) GXReportStatus(kDriverStatus, kSendingData);
  1452.  
  1453.     // error to return from next idle
  1454.     (**hGlobals).idleError = anErr;
  1455.     
  1456. FetchStatusString:        
  1457.     return(anErr);
  1458.     
  1459. } // SD_FreeBuffer
  1460.  
  1461. /* ------------------------------------------------------------------------------------    */
  1462. OSErr SD_DumpBuffer(gxPrintingBuffer * theBuffer)
  1463. {
  1464.     OSErr    anErr;
  1465.     SpecGlobalsHdl    hGlobals = (SpecGlobalsHdl)GetMessageHandlerInstanceContext();
  1466.         
  1467.     if ((**hGlobals).commType == 'PPTL')
  1468.         {
  1469.         unsigned short    statusReturn;
  1470.         anErr = FetchStatusString(&statusReturn, true, true);
  1471.         nrequire(anErr, FetchStatusString);
  1472.         }
  1473.     anErr = Forward_GXDumpBuffer(theBuffer);
  1474.  
  1475. FetchStatusString:        
  1476.     return(anErr);
  1477.     
  1478. } // SD_DumpBuffer
  1479.  
  1480. /* ------------------------------------------------------------------------------------    */
  1481. OSErr SD_StartSendPage(gxFormat pageFormat)
  1482. /*
  1483.     The StartSendPage message is sent just before the page begins to be rendered.
  1484.     
  1485.     Note that the StartSendPage message will not be sent until imaging/communication
  1486.     time, so that user interaction alerts are considered okay here
  1487. */
  1488. {
  1489.     OSErr                        anErr = noErr;
  1490.     gxJob                        theJob = GXGetJob();
  1491.     Collection                    jobCollection;
  1492.     gxPaperType                    thePaperType;
  1493.     gxTrayFeedInfo                trayFeedInfo;
  1494.     long                        itemSize = sizeof(trayFeedInfo);
  1495.     ResType                        commType;
  1496.     unsigned short                statusReturn;
  1497.     
  1498.     check(theJob);
  1499.     jobCollection = GXGetJobCollection(theJob);
  1500.     check(jobCollection);
  1501.     
  1502.     // cache communications type
  1503.     commType = (**(SpecGlobalsHdl)GetMessageHandlerInstanceContext()).commType;
  1504.     if (commType == 'PPTL')
  1505.         {
  1506.         anErr = FetchStatusString(&statusReturn, true, true);
  1507.         nrequire(anErr, FetchStatusString);
  1508.         }
  1509.     else
  1510.         statusReturn = 0;
  1511.         
  1512.     // check to see if this particular page is to be manually fed
  1513.     anErr = GetCollectionItem(jobCollection, gxTrayFeedTag, gxPrintingTagID, &itemSize, &trayFeedInfo);
  1514.     nrequire(anErr, FailedGetCollectionItem);
  1515.             
  1516.     // manual feed or out of paper?  Time to ask the user what to do
  1517.     if     (     trayFeedInfo.manualFeedThisPage
  1518.         ||  ( ( (statusReturn & kOutOfPaperMask) != 0 ) )
  1519.         )
  1520.         {
  1521.         // Wait for all IO to complete, so that we can correctly tell the user what to do.
  1522.         // Since the WriteData message makes sure all data is flushed before performing the
  1523.         // IO, this call insures that pending IO is complete.
  1524.         anErr = Send_GXWriteData(nil, 0);
  1525.         nrequire(anErr, FlushAllData);
  1526.  
  1527.  
  1528.         // then, conduct the alert with the user
  1529.         {
  1530.         gxStatusRecord        *pStat;
  1531.         
  1532.         // make a status record containing the request to the user - note that 
  1533.         // we have to make room for ManualFeedRecord OR OutOfPaperRecord, but manual is bigger
  1534.         pStat = (gxStatusRecord *)NewPtrClear(sizeof(gxStatusRecord)  + sizeof(gxManualFeedRecord));
  1535.         anErr = MemError();
  1536.         nrequire(anErr, NewPtrClear);
  1537.                 
  1538.         pStat->statusOwner    = 'univ';
  1539.         pStat->statResId     = gxUnivAlertStatusResourceId;    // we use the built-in status for this
  1540.         pStat->dialogResult = 0;
  1541.         
  1542.         if (trayFeedInfo.manualFeedThisPage)
  1543.             {
  1544.             gxManualFeedRecord    *pFeed;
  1545.             
  1546.             pStat->statResIndex = gxUnivManualFeedIndex;            // status meaning "manual feed alert"
  1547.             pStat->bufferLen      = sizeof(gxManualFeedRecord);
  1548.             pFeed = (gxManualFeedRecord*)&pStat->statusBuffer;
  1549.         
  1550.             // we can switch to autofeed if we want - and tell the user what kind of paper to load in
  1551.             pFeed->canAutoFeed = true;
  1552.             GXGetPaperTypeName(thePaperType = GXGetFormatPaperType(pageFormat), pFeed->paperTypeName);
  1553.             }
  1554.         else
  1555.             {
  1556.             gxOutOfPaperRecord    *pOut;
  1557.             
  1558.             pStat->statResIndex = gxUnivOutOfPaperIndex;            // status meaning "manual feed alert"
  1559.             pStat->bufferLen      = sizeof(gxOutOfPaperRecord);
  1560.             
  1561.             pOut = (gxOutOfPaperRecord*)&pStat->statusBuffer;
  1562.             GXGetPaperTypeName(GXGetFormatPaperType(pageFormat), pOut->paperTypeName);
  1563.             }
  1564.             
  1565.         // keep sending the user the alert until either
  1566.         //  a) the problem resolves itself
  1567.         //  b) the user responds via the dialog
  1568.         //  c) some other (fatal) error happens
  1569.         do
  1570.             {
  1571.             
  1572.             // tell the user
  1573.             anErr = GXAlertTheUser(pStat);
  1574.             
  1575.             // if the paper got suddenly loaded, do an OK
  1576.             if (commType == 'PPTL')
  1577.                 {
  1578.                 (void) FetchStatusString(&statusReturn, true, true);
  1579.                 if ((statusReturn & kOutOfPaperMask) == 0)
  1580.                     {
  1581.                     pStat->dialogResult = ok;
  1582.                     anErr = noErr;
  1583.                     }
  1584.                 }
  1585.                 
  1586.             } while ((anErr == noErr) && (pStat->dialogResult == 0));
  1587.  
  1588.         // based on the user's response, continue, cancel, or switch to auto feed
  1589.         switch ( pStat->dialogResult )
  1590.             {
  1591.             case ok:
  1592.                 // paper is loaded
  1593.                 break;
  1594.                 
  1595.             case cancel:
  1596.                 // user wishes to stop the printing process
  1597.                 anErr = gxPrUserAbortErr;
  1598.                 break;
  1599.                 
  1600.             case gxAutoFeedButtonId:
  1601.                 // do rest of job with auto feed
  1602.                 
  1603.                 {
  1604.                 gxPaperFeedInfo paperFeed;
  1605.                 
  1606.                 /* Update for job */
  1607.                 paperFeed.autoFeed = true;
  1608.                 (void) AddCollectionItem(jobCollection, gxPaperFeedTag, gxPrintingTagID, sizeof(paperFeed), &paperFeed);
  1609.                 }
  1610.                 
  1611.                 /* Update as it may be reused */
  1612.                 trayFeedInfo.manualFeedThisPage = false;    /* Other trayInfo fields are still valid */
  1613.                 (void) AddCollectionItem(jobCollection, gxTrayFeedTag, gxPrintingTagID, sizeof(trayFeedInfo), &trayFeedInfo);
  1614.                 
  1615.                 /* Can pass paper type reference as this IS device communication time */
  1616.                 anErr = Send_GXCheckStatus((Ptr) &thePaperType, sizeof(thePaperType), 0, 'univ');
  1617.                 ncheck(anErr);
  1618.                 
  1619.                 /* No need to reset tray from gxTrayFeedInfo.feedTrayIndex as there is only one tray! */
  1620.                 break;
  1621.                 
  1622.             } // switch
  1623.             
  1624.             
  1625.         // done with the status now
  1626.         DisposPtr((Ptr) pStat);
  1627.         }
  1628.             
  1629.         } // if manual feed job
  1630.         
  1631.     // display "sending data to the printer" message
  1632.     if (anErr == noErr)
  1633.         anErr = GXReportStatus(kDriverStatus, kSendingData);
  1634.         
  1635.     nrequire(anErr, FailedWaitForPaper);
  1636.         
  1637.     // continue with the standard starting of the page
  1638.     anErr = Forward_GXStartSendPage(pageFormat);
  1639.         
  1640.         
  1641. // FALL THROUGH AND HANDLE EXCEPTIONS
  1642.  
  1643. FailedWaitForPaper:
  1644. NewPtrClear:
  1645. FlushAllData:
  1646. FailedGetCollectionItem:
  1647. FetchStatusString:
  1648.     return(anErr);
  1649.     
  1650. } // SD_StartSendPage
  1651.  
  1652. /* ------------------------------------------------------------------------------------    */
  1653. OSErr SD_FinishSendPage()
  1654. {
  1655.     OSErr        anErr = noErr;
  1656.     Str63        formLength;            // should be more than big enough for form skipping
  1657.     char        len = 0;
  1658.  
  1659.     // we may have issued line feeds RIGHT up to the end of the page.  If
  1660.     // we do that and then issue a form feed, we'll kick out a blank page.
  1661.     // to avoid that, we back up a tad and then let the normal form feed
  1662.     // go through.  Option 2 would be to track each and every motion control
  1663.     // we send to the printer -- but that's more work than this.  In addition,
  1664.     // this method makes sure we are synced up exactly to the hardware
  1665.     formLength[len++] = ESCAPE;
  1666.     formLength[len++] = 'T';
  1667.     formLength[len++] = '0';
  1668.     formLength[len++] = '1';
  1669.     formLength[len++] = ESCAPE;
  1670.     formLength[len++] = 'r';
  1671.     formLength[len++] = 0x0A;
  1672.     
  1673.     // reset to forward motion for the form feed
  1674.     formLength[len++] = ESCAPE;
  1675.     formLength[len++] = 'f';
  1676.     
  1677.     anErr = Send_GXBufferData((char *) &formLength[0], len, gxNoBufferOptions );
  1678.     nrequire(anErr, Send_GXBufferData);
  1679.     
  1680.     // Default implementation provides the actual form feed
  1681.     anErr = Forward_GXFinishSendPage();
  1682.     
  1683. // FALL THROUGH EXCEPTION HANDLING
  1684. Send_GXBufferData:
  1685.  
  1686.     return(anErr);
  1687.     
  1688. } // SD_FinishSendPage
  1689.  
  1690. /* ------------------------------------------------------------------------------------    */
  1691. OSErr SD_JobFormatDialog(gxDialogResult*    theResult)
  1692. /*
  1693.     This message is sent in response to the user's request to put up a formatting dialog
  1694. */
  1695. {
  1696.     OSErr                     anErr;
  1697.     gxJobFormatModeTableHdl    theJobFormatModeList;
  1698.     long                    i;
  1699.     gxJob                     theJob = GXGetJob();
  1700.     
  1701.     // set up the JobFormatMode information
  1702.     
  1703.     anErr = GXGetAvailableJobFormatModes(&theJobFormatModeList);
  1704.     if ((!anErr) && (theJobFormatModeList))
  1705.         {
  1706.         for (i = 0; i <= (*theJobFormatModeList)->numModes - 1; ++i) 
  1707.             {
  1708.             if ((*theJobFormatModeList)->modes[i] == gxTextJobFormatMode) 
  1709.                 {
  1710.                 GXSetPreferredJobFormatMode(gxTextJobFormatMode, false);
  1711.                 break;
  1712.                 }
  1713.             }
  1714.         DisposHandle((Handle)theJobFormatModeList);
  1715.         }
  1716.         
  1717.     // do the normal dialogs after handling the job format mode stuff
  1718.     return(Forward_GXJobDefaultFormatDialog(theResult));
  1719.     
  1720. } // SD_JobFormatModeQuery
  1721.  
  1722. /* ------------------------------------------------------------------------------------    */
  1723. OSErr SD_JobFormatModeQuery(    gxQueryType        theQuery,
  1724.                                 void*            srcData,
  1725.                                 void*            dstData)
  1726. /*
  1727.     This message is sent to find out information about the current job format mode.
  1728. */
  1729. {
  1730.     OSErr        anErr = noErr;
  1731.     Handle        theFonts;
  1732.     Handle        theStyles;
  1733.     
  1734.     check(dstData != nil);
  1735.     
  1736.     // What type of query is being requested?
  1737.     switch(theQuery) 
  1738.     {
  1739.         case gxSetStyleJobFormatCommonStyleQuery:
  1740.         {
  1741.             char                *pStyleName;
  1742.  
  1743.             // Fetch the list of supported styles
  1744.             
  1745.             anErr = Send_GXFetchTaggedDriverData('STR#', kFormatModeStylesID, &theStyles);
  1746.             require(anErr == noErr, FailedToLoadStyles1);
  1747.             
  1748.             HNoPurge(theStyles);
  1749.             HLock(theStyles);
  1750.             
  1751.             // Determine which style is being referenced and set the corresponding style (only 2 styles
  1752.             // are currently supported)
  1753.             
  1754.             if (**((short **) theStyles) == 2)    //    T => We have the correct number of styles
  1755.             {
  1756.                 char        whichFace = 0;
  1757.                 
  1758.                 pStyleName = ((char *) *theStyles) + sizeof(short); 
  1759.                 
  1760.                 if ( IUCompString((unsigned char const *) pStyleName, srcData) == 0 )    //    T => They want bold face
  1761.                 {
  1762.                     whichFace = bold;
  1763.                 }
  1764.                 else
  1765.                 {
  1766.                     // Point to the next name in the list
  1767.                     pStyleName += *pStyleName + 1;
  1768.  
  1769.                     if ( IUCompString((unsigned char const *) pStyleName, srcData) == 0 )    //    T => They want underline face
  1770.                     {
  1771.                         whichFace = underline;
  1772.                     }
  1773.                 }
  1774.  
  1775.                 //    If the client specified a valid face, set it now
  1776.                 if (whichFace != 0)
  1777.                 {
  1778.                     SetStyleCommonFace((gxStyle) dstData, GetStyleCommonFace((gxStyle) dstData) | whichFace);
  1779.                 }
  1780.             }
  1781.             // else - something is wrong with our resource
  1782.             
  1783.             // Dump the temporary handle
  1784.             DisposHandle(theStyles);
  1785.             
  1786.             break;
  1787.         }
  1788.             
  1789.         case gxGetJobFormatFontCommonStylesQuery:
  1790.         {
  1791.             short                numStyles;
  1792.             short                i;
  1793.             char                *pStyleName;
  1794.  
  1795.             // Fetch the list of supported styles
  1796.             
  1797.             anErr = Send_GXFetchTaggedDriverData('STR#', kFormatModeStylesID, &theStyles);
  1798.             require(anErr == noErr, FailedToLoadStyles2);
  1799.             
  1800.             HNoPurge(theStyles);
  1801.             HLock(theStyles);
  1802.             
  1803.             // Determine the number of styles in the list
  1804.             numStyles = **((short **) theStyles);
  1805.  
  1806.             if (*(Handle *)dstData != nil)    //    T => Resize the handle to hold info. on the styles
  1807.                 SetHandleSize(*(Handle *)dstData, sizeof(gxStyleNameTable) + ((numStyles - 1) * sizeof(Str255)));
  1808.             else
  1809.                 *(Handle *)dstData = NewHandle(sizeof(gxStyleNameTable) + ((numStyles - 1) * sizeof(Str255)));
  1810.             
  1811.             anErr = MemError();
  1812.             require(anErr == noErr, StyleTableResizeFailed);
  1813.             
  1814.             // Now extract the name of each of the supported fonts
  1815.             
  1816.             for (i = 1, pStyleName = ((char *) *theStyles) + sizeof(short); i <= numStyles; ++i, pStyleName += *pStyleName + 1)
  1817.             {
  1818.                 BlockMove(pStyleName, (*((gxStyleNameTableHdl) *(Handle *)dstData))->styleNames[i - 1], *pStyleName + 1);
  1819.             }
  1820.             
  1821.             (*((gxStyleNameTableHdl) *(Handle *)dstData))->numStyleNames = numStyles;
  1822.             
  1823.             // Dump the temporary handle
  1824.             DisposHandle(theStyles);
  1825.             
  1826.             break;
  1827.         }
  1828.             
  1829.         case gxGetJobFormatLineConstraintQuery:            //    This type of query is not supported
  1830.             if (*(Handle *)dstData != nil)
  1831.                 SetHandleSize(*(Handle *)dstData, 0);        // Don't return any data
  1832.             break;
  1833.             
  1834.         case gxGetJobFormatFontsQuery:
  1835.         {
  1836.             short                numFonts;
  1837.             short                i;
  1838.             char                *pFontName;
  1839.  
  1840.             // Fetch the list of supported fonts
  1841.             
  1842.             anErr = Send_GXFetchTaggedDriverData('STR#', kFormatModeFontsID, &theFonts);
  1843.             require(anErr == noErr, FailedToLoadFonts);
  1844.             
  1845.             HNoPurge(theFonts);
  1846.             HLock(theFonts);
  1847.             
  1848.             // Determine the number of fonts in the list
  1849.             numFonts = **((short **) theFonts);
  1850.  
  1851.             if (*(Handle *)dstData != nil)    //    T => Resize the handle to hold info. on the fonts
  1852.                 SetHandleSize(*(Handle *)dstData, sizeof(gxFontTable) + ((numFonts - 1) * sizeof(gxFont)));
  1853.             else
  1854.                 *(Handle *)dstData = NewHandle(sizeof(gxFontTable) + ((numFonts - 1) * sizeof(gxFont)));
  1855.             
  1856.             anErr = MemError();
  1857.             require(anErr == noErr, FontTableResizeFailed);
  1858.             
  1859.             // Now generate a reference to each of the supported fonts
  1860.             
  1861.             for (i = 1, pFontName = ((char *) *theFonts) + sizeof(short); i <= numFonts; ++i, pFontName += *pFontName + 1)
  1862.             {
  1863.                 gxFont            thisFont;
  1864.                 gxFontTable        *pFontTable;
  1865.             
  1866.                 thisFont = FindPNameFont(gxFullFontName, (unsigned char const *) pFontName);
  1867.                 
  1868.                 pFontTable = *((gxFontTableHdl) *(Handle *)dstData);
  1869.                 pFontTable->fonts[i - 1] = thisFont;
  1870.             }
  1871.             
  1872.             (*((gxFontTableHdl) *(Handle *)dstData))->numFonts = numFonts;
  1873.             
  1874.             // Dump the temporary handle
  1875.             DisposHandle(theFonts);
  1876.  
  1877.             break;
  1878.         }
  1879.             
  1880.         case gxGetJobFormatFontConstraintQuery:
  1881.         {
  1882.             gxPositionConstraintTable        *pPositionTable;
  1883.             
  1884.             if ( *(Handle *)dstData != nil)    //    T => Resize the handle to hold info. on position constraints
  1885.                 SetHandleSize(*(Handle *)dstData, sizeof(gxPositionConstraintTable) + sizeof(Fixed));
  1886.             else
  1887.                 *(Handle *)dstData = NewHandle( sizeof(gxPositionConstraintTable) + sizeof(Fixed) );
  1888.             
  1889.             pPositionTable = *((gxPositionConstraintTableHdl) *(Handle *)dstData);
  1890.             
  1891.             pPositionTable->phase.x     = 0;                //    Start at the top left corner of the page
  1892.             pPositionTable->phase.y     = 0;
  1893.             pPositionTable->offset.x     = ff(12);        // Indent from the top left by a six lines per inch margin
  1894.             pPositionTable->offset.y     = ff(12);         
  1895.             pPositionTable->numSizes     = 2;                // Two font sizes supported
  1896.             pPositionTable->sizes[0]     = ff(10);         // 10 pitch
  1897.             pPositionTable->sizes[1]     = ff(12);         // 12 pitch
  1898.             
  1899.             break;
  1900.         }
  1901.     } // switch
  1902.     
  1903.     return(anErr);
  1904.     
  1905.  
  1906. /******* Clean-up *******/
  1907.  
  1908. StyleTableResizeFailed:
  1909.     DisposHandle((Handle) theStyles);
  1910.     return(anErr);
  1911.  
  1912. FontTableResizeFailed:
  1913.     DisposHandle((Handle) theFonts);
  1914.  
  1915. FailedToLoadStyles1:
  1916. FailedToLoadStyles2:
  1917. FailedToLoadFonts:
  1918.     return(anErr);
  1919.     
  1920. } // SD_JobFormatModeQuery
  1921.  
  1922. //<FF>
  1923. /* ------------------------------------------------------------------------------------    */
  1924. OSErr SD_SetupImageData(
  1925.     gxRasterImageDataHdl hImageData)        // raster image data stuff
  1926. /*
  1927.     This message is called to setup the constant data used for imaging the entire job.
  1928. */
  1929. {
  1930.  
  1931.     SpecGlobalsHdl                 hGlobals = GetMessageHandlerInstanceContext();
  1932.     OSErr                        anErr;
  1933.     gxRasterImageDataPtr        pImageData;
  1934.     Boolean                     isJobNotFinalQuality, isTextJobFormatMode;
  1935.     long                        imagewriterOptions;
  1936.     
  1937.     // do the default setup
  1938.     anErr = Forward_GXSetupImageData(hImageData);
  1939.     nrequire(anErr, Forward_GXSetupImageData);
  1940.     
  1941.     // test for 'final' quality mode
  1942.     isJobNotFinalQuality = !JobIsBest(&imagewriterOptions);
  1943.     
  1944.     // test for textJobFormatMode
  1945.     isTextJobFormatMode = ( GXGetJobFormatMode( GXGetJob() ) == gxTextJobFormatMode);
  1946.             
  1947.     // if the job is not final quality or using textJobFormatMode, downgrade the imaging data to our lower quality
  1948.     if (isJobNotFinalQuality  ||  isTextJobFormatMode)
  1949.         {
  1950.         // ROUGH OR TEXT MODE
  1951.         
  1952.         // dereference for size and speed    
  1953.         pImageData = *hImageData;
  1954.                 
  1955.         // image at 80 or 72 dpi
  1956.         if (imagewriterOptions & kSuperRes)
  1957.             pImageData->hImageRes = ff(80);
  1958.         else
  1959.             pImageData->hImageRes = ff(72);
  1960.         pImageData->vImageRes = ff(72);
  1961.         
  1962.         // textJobFormatMode loads up the draft table, else setup halftones
  1963.         if (isTextJobFormatMode)
  1964.             {
  1965.             Handle            draftTable;
  1966.  
  1967.             anErr = Send_GXFetchTaggedDriverData('idft', gxPrintingDriverBaseID, &draftTable);
  1968.             nrequire(anErr, FailedToLoadDraftTable);
  1969.             
  1970.             // store away the draft table
  1971.             (**hGlobals).draftTable = draftTable;
  1972.  
  1973.             // Download something?    
  1974.             anErr = Send_GXFetchTaggedDriverData('idft', gxPrintingDriverBaseID+1, &draftTable);
  1975.             if (anErr == resNotFound)
  1976.                 {
  1977.                 draftTable = nil;
  1978.                 anErr = noErr;
  1979.                 }
  1980.             nrequire(anErr, GetDownloadTable);    
  1981.         
  1982.             if (draftTable)
  1983.                 {
  1984.                 HLock(draftTable);
  1985.                 anErr = Send_GXBufferData(*draftTable, GetHandleSize(draftTable), gxDontSplitBuffer);
  1986.                 DisposHandle(draftTable);
  1987.                 nrequire(anErr, SendDownloadTable);
  1988.                 }
  1989.             }
  1990.         else
  1991.             {            
  1992.             // use dither level that will look better at 72 dpi 
  1993.             // resolution than our default values (MAYBE: 4 is the default now anyway)
  1994.             pImageData->theSetup.planeSetup[0].planeHalftone.method = 4;
  1995.             
  1996.             // of course, turn off color matching when in non-final mode!
  1997.             pImageData->theSetup.planeSetup[0].planeProfile = nil;
  1998.             }
  1999.             
  2000.         if (isJobNotFinalQuality)
  2001.             {
  2002.             if (imagewriterOptions & kSuperRes)
  2003.                 {
  2004.                 // use bidirectional instead of unidirectional
  2005.                 // and also <esc>N instead of <esc>p for quality mode
  2006.                 pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+3;
  2007.                 }
  2008.             else
  2009.                 {
  2010.                 // use bidirectional instead of unidirectional
  2011.                 // and also <esc>n instead of <esc>p for quality mode
  2012.                 pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+2;
  2013.                 }
  2014.             }
  2015.         
  2016.         // packaging data
  2017.         pImageData->packagingInfo.headHeight         = 8;        // 8 pins (instead of 16)
  2018.         pImageData->packagingInfo.numberPasses         = 1;        // in 1 head pass (instead of 2)
  2019.         pImageData->packagingInfo.passOffset         = 0;        // with no space between passes
  2020.         }
  2021.     else
  2022.         {
  2023.         // FINAL QUALITY
  2024.         
  2025.         // dereference for size and speed    
  2026.         pImageData = *hImageData;
  2027.                 
  2028.         // image at 160 or 144 dpi
  2029.         if (imagewriterOptions & kSuperRes)
  2030.             {
  2031.             pImageData->hImageRes = ff(160);
  2032.             pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+1;
  2033.             }
  2034.         else
  2035.             {
  2036.             pImageData->hImageRes = ff(144);
  2037.             pImageData->packageControls.startPageStringID = gxPrintingDriverBaseID+0;
  2038.             }
  2039.         }
  2040.     
  2041.     // not a color ribbon?  Setup for black and white - do a B/W halftone rather than a dither
  2042.     if (!PrinterHasColorRibbon(GXGetJobOutputPrinter(GXGetJob())))
  2043.         {
  2044.         // dereference for size and speed    
  2045.         pImageData = *hImageData;
  2046.  
  2047.         // one plane, no color flags, move the halftone info up into correct position
  2048.         pImageData->theSetup.planes = 1;
  2049.         pImageData->theSetup.depth = 1;
  2050.         pImageData->packagingInfo.colorPasses = 1;
  2051.         pImageData->packagingInfo.packageOptions = 0;
  2052.         pImageData->theSetup.planeSetup[0].planeSpace = gxNoSpace;
  2053.         pImageData->theSetup.planeSetup[0].planeSet = nil;
  2054.         pImageData->theSetup.planeSetup[0].planeProfile = nil;
  2055.         pImageData->theSetup.planeSetup[0].planeOptions = gxDefaultOffscreen;
  2056.         pImageData->theSetup.planeSetup[0].planeHalftone.method = gxRoundDot;
  2057.         pImageData->theSetup.planeSetup[0].planeHalftone.tintSpace = gxRGBSpace;
  2058.         }
  2059.  
  2060.     return(noErr);
  2061.     
  2062. // EXCEPTION HANDLING
  2063. SendDownloadTable:
  2064. GetDownloadTable:
  2065.     DisposHandle((**hGlobals).draftTable);
  2066.     (**hGlobals).draftTable = nil;
  2067.     
  2068. FailedToLoadDraftTable:
  2069. Forward_GXSetupImageData:
  2070.     return(anErr);
  2071.     
  2072. } // SD_SetupImageData
  2073.  
  2074. /* ------------------------------------------------------------------------------------    */
  2075. OSErr SD_FetchDriverData(
  2076.     ResType            theType,
  2077.     short            theID,
  2078.     Handle*            theData)
  2079. {
  2080.  
  2081.     OSErr    anErr;
  2082.     
  2083.     anErr = Forward_GXFetchTaggedDriverData(theType, theID, theData);
  2084.     
  2085.     // do the translation at the proper DPI by modifying the old API
  2086.     // customization resource
  2087.     if ( (anErr   == noErr)    &&                 // got the resource okay
  2088.          (theType == 'cust')   &&                // it was a customization resource 
  2089.          (theID   == -8192)   )                    // with the old API id
  2090.         {
  2091.         long imagewriterOptions;
  2092.         
  2093.         if (!JobIsBest(&imagewriterOptions))
  2094.             {
  2095.             **((short**)theData)   = 72;
  2096.             **((short**)theData+1) = 72;
  2097.             }
  2098.         }
  2099.         
  2100.     return(anErr);
  2101.     
  2102. } // SD_FetchDriverData
  2103.  
  2104.  
  2105. /* ------------------------------------------------------------------------------------    */
  2106. OSErr SD_RenderPage(    gxFormat                theFormat,
  2107.                         gxShape                    thePage,
  2108.                         gxPageInfoRecord        *pageInfo,
  2109.                         gxRasterImageDataHdl    imageInfo)
  2110. /*
  2111.     The message sent to render an entire page.
  2112. */
  2113. {
  2114.  
  2115.     OSErr    theError = noErr;
  2116.  
  2117.     // if not text mode, do it the normal (raster) way
  2118.     if (GXGetJobFormatMode(GXGetJob()) != gxTextJobFormatMode) 
  2119.         {
  2120.         gxRectangle            paperSize;
  2121.         Str63                formLength;            // should be more than big enough for form skipping
  2122.         char                aNumber[8];
  2123.         char                len = 0;
  2124.         short                formLen;            // form length (in 144 dpi)
  2125.         short                i;
  2126.         
  2127.         
  2128.         // find out how big our paper is
  2129.         GXGetPaperTypeDimensions(GXGetFormatPaperType(theFormat), nil, &paperSize);
  2130.         
  2131.         // determine the left margin (in pixels)
  2132.         {
  2133.         SpecGlobalsHdl             hGlobals = GetMessageHandlerInstanceContext();
  2134.         SpecGlobalsPtr            pGlobals;
  2135.         gxRasterImageDataPtr    pImageData;
  2136.  
  2137.         check(hGlobals);
  2138.  
  2139.         // dereference for size and speed    
  2140.         pImageData     = *imageInfo;
  2141.         pGlobals = *hGlobals;
  2142.         paperSize.left += ff(18);        // ImageWriter's can't go tighter than .25 inch
  2143.         if (paperSize.left > 0)
  2144.             paperSize.left = 0;
  2145.         pGlobals->leftMargin     = FixedToInt(
  2146.                                     FixMul(-paperSize.left, 
  2147.                                         FixDiv(pImageData->hImageRes, ff(72))));
  2148.         
  2149.         // set this to be the top of form
  2150.         formLength[len++] = ESCAPE;
  2151.         formLength[len++] = 'v';
  2152.  
  2153.         // set the form length to be the size of the page iff ImageWriterII
  2154.         if (pGlobals->isImageWriterII)
  2155.             {
  2156.             formLength[len++] = ESCAPE;
  2157.             formLength[len++] = 'H';
  2158.             formLen = FixedToInt(FixMul(paperSize.bottom-paperSize.top, ff(2)) );    // length is set in 144 dpi
  2159.             NumToString(formLen, (unsigned char *) aNumber);
  2160.             for (i = 0; i < 4-aNumber[0]; ++i)
  2161.                 formLength[len++] = '0';
  2162.             for (i = 1; i <= aNumber[0]; ++i)
  2163.                 formLength[len++] = aNumber[i];
  2164.             }
  2165.         }
  2166.  
  2167.         // NOW: move over the top margin
  2168.         formLen = -FixedToInt( FixMul(paperSize.top, ff(2)) );
  2169.         
  2170.             // Forward line feed
  2171.             formLength[len++] = ESCAPE;
  2172.             formLength[len++] = 'f';
  2173.  
  2174.             // send multiples of 99
  2175.             if (formLen >= 99)
  2176.                 {
  2177.                 formLength[len++] = ESCAPE;
  2178.                 formLength[len++] = 'T';
  2179.                 formLength[len++] = '9';
  2180.                 formLength[len++] = '9';
  2181.                 while (formLen >= 99)
  2182.                     {
  2183.                     formLength[len++] = 0x0A;        // line feed
  2184.                     
  2185.                     formLen -= 99;
  2186.                     }
  2187.                 }
  2188.                 
  2189.             // send remaining line feeds
  2190.             if (formLen > 0)
  2191.                 {
  2192.                 formLength[len++] = ESCAPE;
  2193.                 formLength[len++] = 'T';
  2194.                 NumToString(formLen, (unsigned char *) aNumber);
  2195.                 if (aNumber[0] == 1)
  2196.                     {
  2197.                     formLength[len++] = '0';
  2198.                     formLength[len++] = aNumber[1];
  2199.                     }
  2200.                 else
  2201.                     {
  2202.                     formLength[len++] = aNumber[1];
  2203.                     formLength[len++] = aNumber[2];
  2204.                     }
  2205.                 formLength[len++] = 0x0A;        // line feed
  2206.                 }
  2207.  
  2208.  
  2209.         // we've got all of this data, now send it
  2210.         theError = Send_GXBufferData((char *) &formLength[0], len, gxNoBufferOptions );
  2211.         nrequire(theError, SetFormLength);        
  2212.                 
  2213.         // continue with normal rendering
  2214.         theError = Forward_GXRenderPage(theFormat, thePage, pageInfo, imageInfo);
  2215.         } 
  2216.     else 
  2217.         {
  2218.         theError = PrintPageInDraftMode(thePage, imageInfo);
  2219.         }
  2220.  
  2221. failed_WrongShape:
  2222. SetFormLength:
  2223.     return(theError);
  2224.     
  2225. } // SD_RenderPage
  2226.  
  2227.  
  2228. //<FF>
  2229. /* ------------------------------------------------------------------------------------    */
  2230. /*    SPECIFIC DRIVER RASTER OVERRIDES                                                    */
  2231. /* ------------------------------------------------------------------------------------    */
  2232. OSErr SD_LineFeed (
  2233.     short *lineFeedSize,                         // amount to line feed by
  2234.     Ptr buffer, unsigned long    * bufferPos,     // data goes here
  2235.     gxRasterImageDataHdl hImageData)            // raster image data stuff
  2236. /*
  2237.     Message is sent to output paper advance commands to the printer
  2238. */
  2239. {
  2240.  
  2241.     OSErr    anErr;
  2242.     Boolean    amLowRes;
  2243.     long    actualLineFeed = *lineFeedSize;
  2244.     
  2245.     amLowRes = ((**hImageData).vImageRes == ff(72));
  2246.     // if we are in low res mode, we double the line feed size, as all ImageWriter 
  2247.     // line feed commands are expressed at 144 dpi.
  2248.     if (amLowRes)
  2249.         *lineFeedSize <<= 1;
  2250.     
  2251.     // optimize small motions (particularlly -1 followed by +1 with no data between)
  2252.     // into groups.  This gets rid of the "paper dance" for blank colors passes.
  2253.     {    
  2254.     SpecGlobalsHdl    hGlobals = GetMessageHandlerInstanceContext();
  2255.     SpecGlobalsPtr    pGlobals = *hGlobals;
  2256.     
  2257.     if (    (pGlobals->packagingOptions == kDoSmallLineFeeds) || 
  2258.             (*lineFeedSize < -1) || 
  2259.             (*lineFeedSize > 1) )
  2260.         {
  2261.         *lineFeedSize += pGlobals->lineFeeds;
  2262.         pGlobals->lineFeeds = 0;
  2263.         // do the line feed in the default way
  2264.         anErr = Forward_GXRasterLineFeed(&actualLineFeed, buffer, bufferPos, hImageData);
  2265.         }
  2266.     else
  2267.         {
  2268.         pGlobals->lineFeeds += *lineFeedSize;
  2269.         *lineFeedSize = 0;
  2270.         anErr = noErr;
  2271.         }
  2272.     }
  2273.     
  2274.     // and if in low quality mode, we divide the result to make up for the multiplication
  2275.     // that we do above
  2276.     if (amLowRes)
  2277.         *lineFeedSize >>= 1;    
  2278.             
  2279.     return(anErr);
  2280.     
  2281. } // SD_LineFeed
  2282.  
  2283. //<FF>
  2284. /* ------------------------------------------------------------------------------------    */
  2285. OSErr SD_PackageBitmap (
  2286.     gxRasterPackageBitmapRec    *pPackage,
  2287.     Ptr                         buffer,     // data goes here + bufferPos
  2288.     unsigned long                 *bufferPos,    // how much of the buffer already is full
  2289.     gxRasterImageDataHdl         hImageData)    // private image data
  2290. /*
  2291.     Packages a bitmap for the ImageWriter
  2292.     This routine is called in order to add your rotated and packaged pixel
  2293.     data to the buffer.  It is called once for each head pass.  This routine
  2294.     is pretty complex because it also does IW run length compression.  
  2295.     
  2296.     It must do the following:
  2297.         
  2298.     1)    Start filling the buffer from buffer+bufferPos.  Remember
  2299.         that this pointer may not be word aligned - so be careful
  2300.         assigning things into it.
  2301.         
  2302.     2)    If your printer does SetMargins, put a "fake" set of commands at
  2303.         the begining of the data.  Since most of the time you don't
  2304.         know the margins, you can save away the value of the bufferPos,
  2305.         and backpatch it after you have finished with the offscreen.
  2306.         SetMargins is used on printers that allow you to not send starting
  2307.         and ending whitespace.
  2308.         
  2309.     3)    Add in the rotated data for your printer.  The data to stuff starts
  2310.         at location startY in hOffscreen.  Stuff the bits from here until
  2311.         you reach startY+<your band size>, which is the size of your single
  2312.         band in this resolution mode.  Increment your number by 
  2313.         <your pass offset> + 1, which is the number of microspaces
  2314.         you will send between head passes to form this band.   Take care
  2315.         that you don't step off of the end of the offscreen in this operation,
  2316.         you may be called with startY at the end of the offscreen if the first part
  2317.         of the band is white.
  2318.         
  2319.         colorBand contains the color band which you should be stuffing, from
  2320.         1 to the number of color passes your printer needs (usually 4).
  2321.         Pack in the correct color band.  The packager will call you once
  2322.         for each color band, and correctly handle line feeds and backward
  2323.         line feeds to do the correct thing.  If your printer takes full
  2324.         RGB or CYMK data, I would define your number of colors to be
  2325.         1 and pack the full RGB or CYMK data with the one call to StuffBuffers.
  2326.         
  2327.         If you request kSendAllColors in your raster pack resource, then this
  2328.         message will always be called for all color passes, even those that
  2329.         do not have data on them.  For some printers, this is useful.  For the
  2330.         case of the ImageWriter, this option is not specified, so this message
  2331.         will only be sent for colors that actually have dirty bits within them.
  2332.         
  2333.     4)    Backpatch SetMargins from your saved value in step 2) now that you
  2334.         know the margins.
  2335.         
  2336.     5)    Increment bufferPos by the number of bytes you have
  2337.         added to the buffer.  Be sure to take into account the Set Margins
  2338.         command if you added one.
  2339.  
  2340.     
  2341. */
  2342. {
  2343. #pragma unused (isColorDirty)
  2344.  
  2345.     OSErr                    anErr;                    // would you beleive we could make mistakes?
  2346.     ScanLinePtr                pTheScanLine;            // Pointer to the start of scan line data
  2347.     unsigned short            lastDirtyCol;            // Last dirty part of the scan line
  2348.     unsigned short            firstDirty;                // First dirty pixel
  2349.     unsigned short            lastDirty;                // Last dirty pixel
  2350.     Boolean                    bandIsDirty;            // Is this band dirty?
  2351.     unsigned short            numberBytesAdded;        // Number of bytes we have added to the row
  2352.     unsigned short            repeatCount;            // Number of times we have seen this bitmap
  2353.     
  2354.     register unsigned short    whichCol;                // Index into the scan line data
  2355.     register unsigned short    x,y;                    // Index values into the offscreen
  2356.         
  2357.     register Ptr            thePtr;                    // Pointer to each Y scanline
  2358.     register unsigned char    tempColumn;                // Placeholder for the working column
  2359.     unsigned char            lastColumn;                // What was in the contents of the last column?
  2360.     
  2361.     Ptr                        basePtr;                // Pointer to current X byte
  2362.     unsigned char            outputMask;                // Mask of bit to set in rotated image
  2363.     unsigned char            inputMask;                // Mask of bit to look at in X
  2364.     unsigned char            startingInputMask;        // Mask of first bit of interest
  2365.     unsigned short            yPointerOffset;            // Increment pointer by this to get to next scanline
  2366.     
  2367.     unsigned short            endY, endX, incrY;        // To remove loop invariants.
  2368.     unsigned short            packingColor;            // number of colors packing
  2369.     unsigned long             originalBufferPos;        // where we were in the buffer before we started;
  2370.     long                    originalLineFeeds;        // how many line feeds did we have before?
  2371.     SpecGlobalsHdl            hGlobals = GetMessageHandlerInstanceContext();
  2372.     SpecGlobalsPtr            pGlobals = *hGlobals;
  2373.     
  2374. /* This macro stores one group into the pointer:
  2375.     P = Pointer to fill into
  2376.     G = Character for group
  2377.     S = Length of group run in pixels
  2378. */
  2379. #define EMITGROUP(P, G, S)                    \
  2380.         P->cEscape = ESCAPE;                \
  2381.         P->cCommand = G;                    \
  2382.         Long2Dec(S, P->cLineLength);        
  2383.  
  2384.     // save away original position in order to do a restore should the band be clean
  2385.     originalBufferPos = *bufferPos;
  2386.     originalLineFeeds = pGlobals->lineFeeds;
  2387.     if (originalLineFeeds == 0)
  2388.         {
  2389.         anErr = noErr;
  2390.         }
  2391.     else
  2392.         {
  2393.         // if we have any extra line feeds saved up, do them now!    
  2394.         pGlobals->lineFeeds = 0;
  2395.         pGlobals->packagingOptions = kDoSmallLineFeeds;
  2396.         anErr = Send_GXRasterLineFeed(&originalLineFeeds, buffer, bufferPos, hImageData);
  2397.         pGlobals = *hGlobals;
  2398.         pGlobals->packagingOptions = kNoPackagingOptions;
  2399.         }
  2400.     nrequire(anErr, SendInitialLineFeeds);
  2401.     
  2402.     /* Set color iff ImageWriterII */
  2403.     if ((**hGlobals).isImageWriterII)
  2404.         {
  2405.         pTheScanLine = (ScanLinePtr) (buffer + kSetMarginsSize + (*bufferPos));
  2406.         
  2407.         /* Set color mode for this scan line, if needed */
  2408.         pTheScanLine->cColorEscape        = ESCAPE;
  2409.         pTheScanLine->cSetColorCommand    = kSetColorCommand;
  2410.         
  2411.         packingColor = (*hImageData)->packagingInfo.colorPasses;
  2412.         if (packingColor == 4)
  2413.             switch (pPackage->colorBand)
  2414.                 {
  2415.                 case 1: // yellow
  2416.                     pTheScanLine->cColor    = '1';
  2417.                     startingInputMask = 0x10;
  2418.                     break;
  2419.                     
  2420.                 case 2: // magenta
  2421.                     pTheScanLine->cColor    = '2';
  2422.                     startingInputMask = 0x20;
  2423.                     break;
  2424.     
  2425.                 case 3: // cyan
  2426.                     pTheScanLine->cColor    = '3';
  2427.                     startingInputMask = 0x40;
  2428.                     break;
  2429.                     
  2430.                 case 4: // black
  2431.                     pTheScanLine->cColor    = '0';
  2432.                     startingInputMask = 0x80;
  2433.                     break;
  2434.                     
  2435.                 }
  2436.         else
  2437.             {
  2438.             pTheScanLine->cColor = '0';
  2439.             startingInputMask = 0x80;
  2440.             }
  2441.         }
  2442.     else    /* Backup to eliminate cColorEscape, cSetColorCommand and cColor */
  2443.         {
  2444.         pTheScanLine = (ScanLinePtr) (buffer + kSetMarginsSize + (*bufferPos) - 3);
  2445.         packingColor = (*hImageData)->packagingInfo.colorPasses;
  2446.         startingInputMask = 0x80;
  2447.         }
  2448.  
  2449.     /* Start with the first bit in the offscreen */
  2450.     inputMask = startingInputMask;
  2451.         
  2452.     /* We start out with no dirty bits */
  2453.     firstDirty = 0;
  2454.     lastDirty = 0;
  2455.     bandIsDirty = false;
  2456.     
  2457.     /* Set our array index to zero */
  2458.     whichCol = 0;
  2459.     lastDirtyCol = 0;
  2460.     numberBytesAdded = 0;
  2461.     
  2462.     /* Set up RLL variables */
  2463.     repeatCount = 0;
  2464.     lastColumn = 0;
  2465.     
  2466.     /* Get the byte pointer for the start of this color band */
  2467.     basePtr = pPackage->bitmapToPackage->image;
  2468.     
  2469.     /* Get the byte pointer for the start of the first scan line */ 
  2470.     basePtr += pPackage->startRaster * pPackage->bitmapToPackage->rowBytes;
  2471.             
  2472.     /* Save away loop invariants */
  2473.     endY     = pPackage->startRaster + (*hImageData)->packagingInfo.headHeight;        // Ending scan line
  2474.     incrY     = (*hImageData)->packagingInfo.passOffset + 1;            // Number of scanlines to increment by
  2475.     endX     = pPackage->dirtyRect.right;                                // Ending X pos
  2476.     yPointerOffset = incrY * pPackage->bitmapToPackage->rowBytes;            // amount to add to the input
  2477.                                                             // pointer to move to the next scanline
  2478.  
  2479.     /* If the ending position is too large for the bitmap we have been given,
  2480.        truncate it, so that we don't print garbage */
  2481.     if (endY > pPackage->bitmapToPackage->height)
  2482.         endY = pPackage->bitmapToPackage->height;
  2483.     
  2484.     /* For the entire width of the offscreen, move a rolling mask along in the
  2485.        X direction, rotating up 8 bits of Y data per column.  In addition, compress
  2486.        runs of columns that are > 14 length. */
  2487.     for (x = 0; x < endX; x++)
  2488.         {        
  2489.         /* The bits in this column are clear to begin with */
  2490.         tempColumn = 0;
  2491.         
  2492.         /* Which byte to look at in the input buffer */
  2493.         thePtr = basePtr;
  2494.         
  2495.         /*     Where to place the bit in the output. The ImageWriter takes the bit
  2496.             pattern upside down. */
  2497.         outputMask = 0x01;
  2498.         
  2499.         /* Scan through this band, setting each of the 8 bits == the bit in that scan line */
  2500.         for (y = pPackage->startRaster; y < endY; y += incrY)
  2501.             {
  2502.             /* If we have a bit in the input, rotate it into the output */
  2503.             if ((*thePtr) & inputMask)
  2504.                 tempColumn |= outputMask;
  2505.  
  2506.             // move onto next position in the output data                
  2507.             outputMask <<= 1;
  2508.             
  2509.             // move onto the next scan line in the input data
  2510.             thePtr += yPointerOffset;
  2511.             } // for y
  2512.             
  2513.             
  2514.         /* Save the column info */ 
  2515.         pTheScanLine->iTheData[whichCol] = tempColumn;
  2516.         
  2517.         /* Get the next bit from the current pointer */
  2518.         inputMask >>= packingColor;
  2519.         if (!inputMask)
  2520.             {
  2521.             /* If we run out of bits, get the next byte */
  2522.             basePtr++;
  2523.             
  2524.             /* And reset the bit mask to the first bit */
  2525.             inputMask = startingInputMask;
  2526.             }
  2527.             
  2528.         /* If we have some form of data */
  2529.         if (tempColumn != 0)
  2530.             {
  2531.             if (!bandIsDirty)
  2532.                 {
  2533.                 /* This is the first dirty pixels we have so far */
  2534.                 bandIsDirty = true;
  2535.                 firstDirty = x;
  2536.                 }
  2537.             
  2538.             /* This is also the last dirty pixels so far */
  2539.             lastDirty = x;
  2540.             } // SetDirty
  2541.             
  2542.         /* If we have some dirty bits */
  2543.         if (bandIsDirty)
  2544.             {
  2545.             /* Move on to the next column */
  2546.             whichCol++;
  2547.             
  2548.             /* If this is a dirty column, then it is the last one so far */
  2549.             if (tempColumn != 0)
  2550.                 lastDirtyCol = whichCol;
  2551.             
  2552.             /* If we have a duplication, up the repeat count */
  2553.             if (tempColumn == lastColumn) // if (false) // turn off repeat groups
  2554.                 {
  2555.                 repeatCount++;
  2556.                 if (repeatCount == 14)
  2557.                     {
  2558.                     /* Kick out the old group */
  2559.                     whichCol -= 14;
  2560.                         EMITGROUP(pTheScanLine, kGraphicsCommand, whichCol);
  2561.                         numberBytesAdded += whichCol + kGroupSize;
  2562.                         pTheScanLine = (ScanLinePtr)(((Ptr) pTheScanLine) +
  2563.                             whichCol + kGroupSize);
  2564.                     
  2565.                     whichCol = 1;
  2566.                     lastDirtyCol = 1;
  2567.                     pTheScanLine->iTheData[0] = tempColumn;
  2568.                     }
  2569.                 }
  2570.             else
  2571.                 {
  2572.                 /* If we were repeating, emit the repeat group */
  2573.                 if (repeatCount >= 14)
  2574.                     {
  2575.                     EMITGROUP(pTheScanLine, kRepeatGroup, repeatCount);
  2576.                     numberBytesAdded += 1 + kGroupSize;
  2577.                     pTheScanLine = (ScanLinePtr) (((Ptr) pTheScanLine) + 
  2578.                         1 + kGroupSize);
  2579.                         
  2580.                     whichCol = 1;
  2581.                     lastDirtyCol = 1;
  2582.                     pTheScanLine->iTheData[0] = tempColumn;
  2583.                     }
  2584.                 repeatCount = 0;
  2585.                 lastColumn = tempColumn;
  2586.                 }
  2587.                 
  2588.             } // BandIsDirty
  2589.             
  2590.         } // end of loop for width of bitmap
  2591.  
  2592.     /* if we have a dirty band - emit the final bit of data we have
  2593.        packaged up */
  2594.     if (bandIsDirty)
  2595.         {            
  2596.         
  2597.         /* Set the margins to be the first and last dirty pixels in the scan line -
  2598.            the ImageWriter only does left margin optimization. */
  2599.         {
  2600.             SetMarginsPtr        marginBuffer;
  2601.             SpecGlobalsHdl         hGlobals = GetMessageHandlerInstanceContext();
  2602.             
  2603.             check(hGlobals);
  2604.             
  2605.             /* Get the location for placing the set margin command */
  2606.             marginBuffer = (SetMarginsPtr) (buffer + (*bufferPos));
  2607.             
  2608.             /* Stuff in the set margin command */
  2609.             marginBuffer->cEscape  = ESCAPE;
  2610.             marginBuffer->cCommand = kSetMarginsCommand;
  2611.             
  2612.             /* convert left margin into ASCII and place it at the start of the buffer */
  2613.             Long2Dec((**hGlobals).leftMargin + firstDirty, (Ptr)(marginBuffer->cIndentDistance));
  2614.         }
  2615.         
  2616.         /* Send the last group command */
  2617.         if (repeatCount < 14)
  2618.             {
  2619.             /* Emit a normal group */
  2620.             EMITGROUP(pTheScanLine, kGraphicsCommand, lastDirtyCol);
  2621.             numberBytesAdded += lastDirtyCol + kGroupSize;
  2622.             }
  2623.         else
  2624.             {
  2625.             /* Don't stuff a final repeat group if it's blank space */
  2626.             if (tempColumn != 0)
  2627.                 {
  2628.                 /* Emit a repeat group */
  2629.                 EMITGROUP(pTheScanLine, kRepeatGroup, repeatCount);
  2630.                 numberBytesAdded += 1 + kGroupSize;
  2631.                 }
  2632.             } // end of repeatCount < 14
  2633.                     
  2634.         
  2635.         /*    Increment the count of the buffer by bytes added for groups, plus
  2636.             the header, if any, plus the set margins command */
  2637.         (*bufferPos) += numberBytesAdded + kScanLineSize + kSetMarginsSize;
  2638.  
  2639.         /* and put a <cr> at the end of the line */
  2640.         *(char*)(buffer + (*bufferPos)) = '\n';
  2641.         (*bufferPos) += 1;
  2642.         
  2643.         } // bandIsDirty
  2644.     else
  2645.         {
  2646.         // don't output data if we didn't have any!
  2647.         *bufferPos = originalBufferPos;
  2648.  
  2649.         // restore original number of line feeds
  2650.         pGlobals = *hGlobals;
  2651.         pGlobals->lineFeeds = originalLineFeeds;
  2652.         } // band is not dirty
  2653.         
  2654.     // always return your errors!
  2655. SendInitialLineFeeds:
  2656.     return(anErr);
  2657.     
  2658. } // SD_PackageBitmap
  2659.